Middle-题目84:82. Remove Duplicates from Sorted List II

原创 2016年05月31日 17:14:32

题目原文:
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.
题目大意:
给出一个排序好的链表,删除所有重复元素,只保留一个,且保持原来的顺序。
题目分析:
维护两个指针p1和p2,其中p2指向p1下一个节点,每次判断p1和p2的值是否相等,如果相等则删掉p2,且p2向后推,直到p2不等于p1,再令p1等于p2继续判断,总共扫描一遍链表即可。
源码:(language:c)

struct ListNode* deleteDuplicates(struct ListNode* head) {
     if (!head || !head->next)
         return head;
     else {
         struct ListNode* ptr1 = head, *ptr2 = head;
         while (ptr2) {
             ptr1 = ptr2;
             while (ptr2 && ptr2->val == ptr1->val)
                 ptr2 = ptr2->next;
             if (ptr1->next == ptr2)  // no duplicate
                 ptr1 = ptr2;
             else if (ptr1 == head)
                 head = ptr2;
             else {
                 struct ListNode* prev = head;
                 while (prev->next != ptr1)
                     prev = prev->next;
                 prev->next = ptr2;
                 ptr1 = ptr2;
             }
         }

         return head;
     }
 }

成绩:
4ms,beats 8.00%,众数4ms,92%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode82:Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct num...

【一天一道LeetCode】#82. Remove Duplicates from Sorted List II

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目...

LeetCode - 82. Remove Duplicates from Sorted List II

这一道题目主要是链表的操作,一开始因为情况比较复杂,把自己绕晕了,所以没想到这道题目的解法,后来看了答案才觉得自己解起来确实很难解出。这道题目对于链表的操作比较复杂,所要考虑的情况也很多,最大的一个技...

leetcode_82_Remove Duplicates from Sorted List II

思路: 大致思路就是,遍历链表找出重复元素的子列并删除重复元素子列,当然,第一个元素开始有重复元素的话比较特种,需要特殊考虑。删除子列的过程稍微有点绕,题目倒是不难理解。...

[leetcode 82]Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb...

LeetCode 82. Remove Duplicates from Sorted List II pre指针,首元素的处理

题目 题意 注意 思路 代码 结果题目 Given a sorted linked list, delete all nodes that have duplicate numbers, leav...

[leetcode] 82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb...

[LeetCode]82.Remove Duplicates from Sorted List II

【题目】 Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distin...

leetcode || 82、Remove Duplicates from Sorted List II

problem: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onl...

[LeeCode] 82. Remove Duplicates from Sorted List II java

/**82. Remove Duplicates from Sorted List II * @param head * @return 出现次数>=2的数字全不要 */...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目84:82. Remove Duplicates from Sorted List II
举报原因:
原因补充:

(最多只允许输入30个字)