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. 

代码:

class Solution {

public:

  ListNode *deleteDuplicates(ListNode *head) {

    if (head == NULL) {

      return NULL;

    }

    ListNode dummy(-1);

    dummy.next = head;

    ListNode *prev = &dummy;

    ListNode *cur = head;

    while (cur != NULL) {

      bool duplicated = false;

      while (cur->next != NULL && cur->val == cur->next->val) {

        duplicated = true;

        ListNode *tmp = cur;

        cur = cur->next;

        delete tmp;

      }

      if (duplicated) {  //删除重复的最后一个元素

        ListNode *tmp = cur;

        cur = cur->next;

        delete tmp;

        continue;

      }

      prev->next = cur;

      prev = prev->next;

      cur = cur->next;

    }

    prev->next = cur;

    return dummy.next;

  }

};

posted @ 2017-12-14 09:35  飘舞的雪  阅读(74)  评论(0编辑  收藏  举报