Given a sorted linked list, delete all duplicates such that each element appear only once.
For example, given 1->1->2, return 1->2; given 1->1->2->3->3, return 1->2->3.
http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
Solution:
Pretty straight forward. Start from head and check if next node -> val is equal to current node -> val.
If we need to remove the next node, change the current -> next to current -> next -> next. Be careful about some edge cases.
https://github.com/starcroce/leetcode/blob/master/remove_duplicates_from_sorted_list.cpp
// 76 ms for 164 test case
// Given a sorted linked list, delete all duplicates such that each element appear only once.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head == NULL) {
return NULL;
}
ListNode *node = head;
ListNode *next_node = head->next;
while(next_node != NULL) {
if(node->val == next_node->val) {
ListNode *tmp = next_node;
next_node = next_node->next;
node->next = next_node;
continue;
}
node = node->next;
next_node = next_node->next;
}
return head;
}
};