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

[LeetCode] Remove Duplicates from Sorted List

时间:2015-05-07 16:54:03      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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);
        myHead->next = head;
        ListNode *p=myHead, *q;
        while(p->next!=NULL&&p->next->next!=NULL){
            if(p->next->val == p->next->next->val){
                q=p->next;
                p->next = p->next->next;
                delete q;
            }else{
                p=p->next;
            }
        }
        p=myHead;
        myHead=myHead->next;
        delete p;
        return myHead;
    }
};


[LeetCode] Remove Duplicates from Sorted List

标签:c++   leetcode   

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

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