删除链表中重复的结点 Delete duplicated nodes in linked list

来源:互联网 发布:ffmpeg java调用 编辑:程序博客网 时间:2024/06/04 18:50

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。例如,链表 1->2->3->3->4->4->5 处理后为 1->2->5

题解

这题看似很简单,但是务必考虑如下情形:

  • 1->1
  • 1->1->2->2
  • 1->2->2->3->3
  • 空链表

另外,遍历链表千万不要为了简洁写成for循环!我因为这个出了bug,看了很久才看出来。

代码

class Solution {    ListNode* dedup(ListNode* head) {        int val = head->val;        while (head && head->val == val) {            head = head->next;        }        return head;    }public:    ListNode* deleteDuplication(ListNode* pHead) {        if (pHead == NULL) return NULL;        ListNode *p = pHead, *pBefore = NULL;        while (p != NULL) {            if (p->next && p->next->val == p->val) {                if (pBefore) {                    pBefore->next = dedup(p);                    p = pBefore->next;                    continue;                } else {                    pHead = dedup(p);                    p = pHead;                    continue;                }            }            pBefore = p;            p = p->next;        }        return pHead;    }};
0 0
原创粉丝点击