-
Notifications
You must be signed in to change notification settings - Fork 62
/
SingleLinkedList.java
94 lines (84 loc) · 1.85 KB
/
SingleLinkedList.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package datastructure.linkedlist;
/**
* @author roseduan[roseduan520@gmail.com]
* @time 2019/10/19 22:20
* @description 单链表基本实现
*/
public class SingleLinkedList {
private ListNode head;
private SingleLinkedList(int val) {
this.head = new ListNode(val);
}
private static class ListNode{
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
/**
* 查找节点
*/
public ListNode find(int value){
if (head == null){
return null;
}
ListNode p = head;
while (p != null && p.val != value){
p = p.next;
}
return p;
}
/**
* 插入元素
*/
public ListNode add(int value) {
ListNode node = new ListNode(value);
if (head == null) {
head = node;
}
else {
ListNode p = head;
while (p.next != null){
p = p.next;
}
p.next = node;
}
return head;
}
/**
* 删除元素
*/
public boolean remove(int value){
if (head == null){
return false;
}
ListNode prev = null;
ListNode p = head;
while (p != null && p.val != value){
prev = p;
p = p.next;
}
if (p == null){
return false;
}
if (prev == null){
head = head.next;
}
else {
prev.next = p.next;
}
return true;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
ListNode p = head;
while (p != null){
result.append(p.val).append(" ");
p = p.next;
}
return result.toString();
}
}