循环链表的插入删除

参考:https://www.cnblogs.com/lixiaolun/p/4643911.html

1、循环链表的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package circularList;

public class CircularLinkList {

Node head;//头节点

//初始化
public void init() {
head=new Node();
head.data=null;
head.next=null;
}

//插入
public void insert(String e) {
//如果是第一次插入
Node node=new Node();
node.data=e;

if(head.next==null) {
head.next=node;
node.next=head;
}else {
Node temp=head;
while(temp.next!=head) {
temp=temp.next;
}

temp.next=node;
node.next=head;
}
}

//删除
public void delete(String e) {
Node temp=head;

while(temp.next!=head)
{
//判断temp当前指向的结点的下一个结点是否是要删除的结点
if(temp.next.data.equals(e))
{
temp.next=temp.next.next;//删除结点
}else
{
temp=temp.next;//temp“指针”后移
}

}

}

public void printNode() {
Node node=head;

while(node.next!=head) {
node=node.next;
System.out.println(node.data);
}
}

class Node{
String data;
Node next;
}
}

2、测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package circularList;

public class TestCircularList {

public static void main(String[] args) {
// TODO Auto-generated method stub

CircularLinkList list=new CircularLinkList();
list.init();
list.insert("ct");
list.insert("ad");
list.insert("oo");
//list.delete("ad");

list.printNode();
}

}