单链表的插入删除

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
package danlianbiao;

public class Linklist {

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;
}else {
Node temp=head;
while(temp.next!=null) {
temp=temp.next;
}

temp.next=node;
}
}

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

while(temp.next!=null)
{
//判断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!=null) {
System.out.println(node.next.data);
node=node.next;
}
}

class Node{
String data;
Node next;
}

}

2、测试类

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

public class TestLink {

public static void main(String[] args) {
Linklist link=new Linklist();
link.init();
link.insert("ct");
link.insert("ad");
link.insert("oo");
//link.delete("ad");

link.printNode();
}

}

3、参考链接:https://www.cnblogs.com/lixiaolun/p/4643886.html