-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkList.java
More file actions
78 lines (63 loc) · 1.36 KB
/
Copy pathLinkList.java
File metadata and controls
78 lines (63 loc) · 1.36 KB
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
public class LinkList {
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Node head;
public LinkList() {
head = null;
}
public void addFirst(int x) {
Node n = new Node(x);
n.next = head;
head = n;
}
public void addLast(int x) {
Node n = new Node(x);
if (head == null) {
head = n;
return;
}
Node cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = n;
}
public void delete(int x) {
if (head == null)
return;
if (head.data == x) {
head = head.next;
return;
}
Node cur = head;
while (cur.next != null && cur.next.data != x) {
cur = cur.next;
}
if (cur.next != null) {
cur.next = cur.next.next;
}
}
public void printList() {
Node cur = head;
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
System.out.println();
}
public int size() {
int cnt = 0;
Node cur = head;
while (cur != null) {
cnt++;
cur = cur.next;
}
return cnt;
}
}