资源描述
学习数据结构已经三天,刚开始自然遇到线性表。其中线性表内含顺序表和链表。顺序表较为简单,仅仅需要一个数组就可以完成,当然最好也要添加一个表示长度的数据成员,如size。而链表,显然比较多变看,小可不才,用了将近三天的时间才能明白,不能不说见笑于大方之家;皆因链表之中还有循环链表,双向链表,双向循环链表。好了,言归正传:循环链表的程序奉上:
链表,不过增(insert)删(delete)改(update)查(select)而已。在于Java程序中,还要加上构造(Java有垃圾回收机制,故没有析构,但可以手动回收)。先看代码如下:
1、关于构造函数,小生理解到:需要什么样的初始化,就写出什么样的构造函数,当然,没有时也可以构造一个空的构造函数;本人就节点有一个构造函数
2、在方法中,注意index的具体代表就行。其中,在找上一节点时,很多重复了,可以另外写入一个函数中。
3、最后只是一个测试形式的,可以自己设置
4、自认为一个比较简单的程序了
package link;
class Node {
public int num;
public Node next;
public Node(int num, Node next) {
this.num = num;
this.next = next;
}
}
public class CycleList {
public Node head;
public int size;
public void insertHead(int element){ //在头结点的地方插入 if(size == 0){
head = new Node(element, null);
head. next = head;
}else {
Node no = head;
head = new Node(element, no);
}
size ++;
}
public void insert(int index, int element) { //插入元素
if (size == 0) {
head = new Node(element, head);
} else {
if (index < 0) {
index = 0;
}
if (index > size) {
index = size;
}
Node no1 = head;
for (int i = 0; i < index - 1; i++) {
no1 = no1.next;
}
Node no2 = new Node(element, no1.next);
no1.next = no2;
}
size++;
}
public void delete(int index) { // 删除函数
if (index < 0) {
index = 0;
}
if (index > size) {
index = size;
}
Node no3 = head;
for (int i = 0; i < index - 1; i++) {
no3 = no3.next;
}
no3.next = no3.next.next;
size--;
}
public void select() { // 查询所有元素
int sizelong = size;
Node no4 = head;
for (int i = 0; i < sizelong; i++) {
System.out.print(no4.num);
no4 = no4.next;
}
}
public void update(int index, int element){ //更换index位置的内容
Node no7 = head;
for(int i=0; i<index-1; i++){
no7 = no7.next;
}
no7.num = element;
}
public void sel(int index){ //查询index位置的内容
Node no8 = head;
for(int i=0; i<index-1; i++){
no8 = no8.next;
}
System.out.println(no8.num);
}
public static void main(String[] args) {
CycleList cl = new CycleList();
cl.insert(0, 4); // index 代表第几个后面,当然,第0个后面,即为插头节点
cl.insert(2, 2); // 无论插入还是删除
cl.insert(3, 5); //更改很准确
cl.insert(4, 6); // 查询单个也是可以的
cl.insert(5, 9);
cl.select();
System.out.print(" ----");
cl.insert(0, 8);
cl.select();
System.out.print(" ----");
cl.insertHead(3);
cl.select();
System.out.println("------");
cl.delete(3);
cl.select();
System.out.println("---------");
cl.update(1, 1);
cl.select();
System.out.print("----");
cl.sel(0);
}
}
展开阅读全文