码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Remove Duplicates from Sorted List II

时间:2015-08-03 19:22:47      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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.

解题思路:

这道题的题意是删除有序链表中所有出现两次或两次以上的元素。本身没有较大的难度,注意第一个元素可能是重复元素的情况。

/**
 * 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* myHead=new ListNode(0);
        ListNode* tail = myHead->next;
        ListNode* preTail = myHead;
        ListNode* p = head, *q;
        while(p!=NULL){
            if(tail==NULL){
                tail = p;
                preTail->next = tail;
                p=p->next;
                tail->next = NULL;
            }else if(tail->val != p->val){
                tail->next = p;
                p=p->next;
                tail = tail->next;
                tail->next = NULL;
                preTail = preTail->next;
            }else{
                while(p!=NULL && tail->val == p->val){
                    q = p;
                    p=p->next;
                    delete q;
                }
                delete tail;
                tail = NULL;
                preTail->next=NULL;
            }
        }
        p=myHead;
        myHead = myHead->next;
        delete p;
        return myHead;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Remove Duplicates from Sorted List II

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47258315

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!