双向循环链表的插入删除

参考:https://www.cnblogs.com/lixiaolun/p/4643931.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 doubleList;

public class DoubleLinkList {

Node head;//头节点

public void init() {
head=new Node();
head.data=null;
head.prev=head;
head.next=head;
}

//插入
public void insert(String e) {
Node node=new Node();
node.data=e;
//第一次插入
if(head.prev==head) {
head.next=node;
head.prev=node;
node.prev=head;
node.next=head;

}else {
//末尾插入
Node temp=head;
while(temp.next!=head) {
temp=temp.next;
}

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

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

while(temp.next!=head) {
if(temp.next.data.equals(e)) {
temp.next=temp.next.next;
temp.next.prev=temp;
}
temp=temp.next;
}

}

public void printNode() {
Node node=head;

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

class Node{
String data;
Node prev;
Node next;
}
}

2、测试类

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

public class TestDoubleList {

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

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

list.printNode();
}

}