-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListNode Practice
More file actions
100 lines (86 loc) · 2.71 KB
/
Copy pathLinkedListNode Practice
File metadata and controls
100 lines (86 loc) · 2.71 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class LinkedListNode
{
// public Object data;
// public LinkedListNode next;
//
// public LinkedListNode(Object data) {
// this.data = data;
// }
LinkedListNode next = null;
int data;
public LinkedListNode(int d) {
data = d;
}
void appendToTail(int d){
LinkedListNode end = new LinkedListNode(d);
LinkedListNode n = this;
while(n.next != null){
n = n.next;
}
n.next = end;
}
public static void main(String[] args)
{
// LinkedListNode node_1 = new LinkedListNode("first");
// LinkedListNode node_2 = new LinkedListNode("second");
// node_1.next = node_2;
// LinkedListNode node_3 = new LinkedListNode("third");
// node_2.next = node_3;
LinkedListNode node_1 = new LinkedListNode(1);
LinkedListNode node_2 = new LinkedListNode(2);
node_1.next = node_2;
LinkedListNode node_3 = new LinkedListNode(3);
node_2.next = node_3;
System.out.println("*** Print contents of linked list");
LinkedListNode current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("*** Print contents of linked list from node_2");
current = node_2;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("***Now appendToTail0001");
node_1.appendToTail(10);
current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("***Now appendToTail0002");
node_2.appendToTail(20);
current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("***Now appendToTail0003");
node_3.appendToTail(30);
current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("*** Now delete second node");
deleteNode(node_2);
System.out.println("*** Print after deleting second node");
current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
public static boolean deleteNode(LinkedListNode n)
{
if (n == null || n.next == null) {
return false; // Failure
}
LinkedListNode next = n.next;
n.data = next.data;
n.next = next.next;
return true;
}
}