-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample1.java
85 lines (60 loc) · 2.13 KB
/
Example1.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
package applications.algorithms;
import datastructs.adt.SingleLinkedList;
/** Category: Algorithms
* ID: Example 1
* Description: Delete duplicated elements from sorted linked list
* Taken From: Question 44 Coding Interviews Questions, Analysis and Solutions
* Details:
* TODO
*/
public class Example1 {
public static void deleteDuplicateElements(SingleLinkedList<Integer> list){
SingleLinkedList<Integer>.Node previous = null;
SingleLinkedList<Integer>.Node current = list.front();
SingleLinkedList<Integer>.Node head = list.front();
while(current != null){
SingleLinkedList<Integer>.Node next = current.getNext();
boolean needDelete = false;
if(next != null && next.getData().equals(current.getData())){
needDelete = true;
}
if(!needDelete){
// simply move forward
previous = current;
current = next;
}
else{
int value = current.getData();
SingleLinkedList<Integer>.Node toBeDeleted = current;
while(toBeDeleted != null && toBeDeleted.getData().equals(value)) {
next = toBeDeleted.getNext();
toBeDeleted = null;
toBeDeleted = next;
}
if(previous == null) {
head = next;
}
else {
previous.setNext(next);
}
current = next;
}
}
}
public static void main(String[] args){
SingleLinkedList<Integer> list = new SingleLinkedList<>();
// create a sorted linked list
list.pushBack(1);
list.pushBack(2);
list.pushBack(3);
list.pushBack(3);
list.pushBack(4);
list.pushBack(4);
list.pushBack(5);
System.out.println("List before removing duplicates: \n");
list.print();
Example1.deleteDuplicateElements(list);
System.out.println("\nList after removing duplicates: \n");
list.print();
}
}