82. Remove Duplicates from Sorted List II

来源:互联网 发布:ai mac中文版免费下载 编辑:程序博客网 时间:2024/06/05 16:23

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.

思路
类似于83题,不过这里重复元素都要删掉,涉及到头节点可能会删掉的问题,需要定义一个辅助节点

代码(C)

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* deleteDuplicates(struct ListNode* head) {    if (NULL == head)        return head;    struct ListNode* helper = (struct ListNode*)malloc(sizeof(struct ListNode));//辅助指针    helper->next = head;    struct ListNode* pre = helper;    struct ListNode* cur = head;    while (cur)    {        while (cur->next != NULL && pre->next->val == cur->next->val)            cur = cur->next;        if (pre->next == cur)//没有重复的,则pre 和 cur都向后移动一位            pre = pre->next;        else             pre->next = cur->next;//有重复的话,pre的下一个节点指向当前节点的下一个节点,相当于中间都删除了        cur = cur->next;    }    return helper->next;}

循环那段不明白的话画幅图走一遍就清楚了。

0 0
原创粉丝点击