-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathcd14
More file actions
83 lines (71 loc) · 1.69 KB
/
cd14
File metadata and controls
83 lines (71 loc) · 1.69 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
// Java program to remove duplicates from a sorted linked list
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
void removeDuplicates()
{
/*Another reference to head*/
Node curr = head;
/* Traverse list till the last node */
while (curr != null) {
Node temp = curr;
/*Compare current node with the next node and
keep on deleting them until it matches the current
node data */
while(temp!=null && temp.data.equals(curr.data)) {
temp = temp.next;
}
/*Set current node next to the next different
element denoted by temp*/
curr.next = temp;
curr = curr.next;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
/* Driver program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
System.out.println("List before removal of duplicates");
llist.printList();
llist.removeDuplicates();
System.out.println("List after removal of elements");
llist.printList();
}
}
/* This code is contributed by Rajat Mishra */