- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListNode.java
More file actions
Latest commit
106 lines (90 loc) · 2.08 KB
/
Copy pathLinkedListNode.java
File metadata and controls
106 lines (90 loc) · 2.08 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
100
101
102
103
104
105
106
packagecracking.coding;
publicclassLinkedListNode {
intdata;
LinkedListNodenext;
publicLinkedListNode(intdata){
this.data=data;
this.next=null;
}
publicvoidaddToList(intdata){
LinkedListNodenode = newLinkedListNode(data);
LinkedListNodehead = this;
while(head.next !=null){
head = head.next;
}
head.next=node;
}
publicLinkedListNodedelete(LinkedListNodehead, intdata){
LinkedListNodenode=head, temp;
if(node.data==data){
returnnode.next;
}
while(node.next != null){
if(node.next.data==data){
node.next=node.next.next;
returnhead;
}
node=node.next;
}
returnhead;
}
publicvoidprintData(LinkedListNodehead){
LinkedListNodenode=head;
while(node != null){
System.out.println("--> "+node.data);
node=node.next;
}
}
publicstaticvoidmain(String [] args){
LinkedListNodehead = newLinkedListNode(1);
head.addToList(2);
head.addToList(3);
head.addToList(4);
head.addToList(5);
head.addToList(5);
head.addToList(4);
head.addToList(6);
head.addToList(4);
head.addToList(6);
head.printData(head);
//head.removeDuplicates(head);
//head.printData(head);
head.kthLastElement(head, 6);
}
publicLinkedListNoderemoveDuplicates(LinkedListNodehead){
LinkedListNodecurrent;
current = head;
while(current != null){
LinkedListNoderunner = current.next;
LinkedListNodeprevious = current;
while(runner != null){
if(current.data == runner.data){
LinkedListNodetmp;
tmp = runner.next;
previous.next = tmp;
}
previous = runner;
runner = runner.next;
}
current = current.next;
}
returnhead;
}
publicvoidkthLastElement(LinkedListNodehead, intn){
intcount = 1;
LinkedListNodenode=head, target=head;
while (count <= n && node != null){
node = node.next;
count ++;
}
if(node == null){
System.out.println("index does not exist");
System.exit(1);
}
while(node != null){
target = target.next;
node = node.next;
}
System.out.println("The "+n+"th value from last is "+target.data);
}
}