Remove Duplicates
Write a removeDuplicates() function which takes a list and deletes any duplicate nodes from the list. The list is not sorted.
Example
if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.
Note
排序(merge sort)+双指针
哈希Set
Code
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 current = head;
/* Pointer to store the next pointer of a node to be deleted*/
Node next_next;
/* do nothing if the list is empty */
if (head == null)
return;
/* Traverse list till the last node */
while (current.next != null) {
/*Compare current node with the next node */
if (current.data == current.next.data) {
next_next = current.next.next;
current.next = null;
current.next = next_next;
}
else // advance if no deletion
current = current.next;
}
}
}Last updated