Remove Duplicates from Sorted List II


Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Solution: need to keep track of the previous node, since you want to delete all duplicate nodes.
The following code passes LeetCode Online Large Judge.
/**
 * 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) {
        ListNode *temp = new ListNode(0);
        temp->next = head;
        ListNode *prev = temp, *curr = head;
        while(curr != NULL) {
            bool flag = false;
            while(curr->next != NULL && curr->val == curr->next->val) {
                flag = true;
                curr = curr->next;
            }
            if(flag) prev->next = curr->next;
            else prev = curr;
            curr = curr->next;
        }
        return temp->next;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 4 Trees and Graphs