码迷,mamicode.com
首页 > 编程语言 > 详细

LintCode 112. 删除排序链表中的重复元素

时间:2018-01-28 11:23:57      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:lin   class   dup   lint   bsp   code   blog   null   turn   

给定一个排序链表,删除所有重复的元素每个元素只留下一个。

 样例

给出 1->1->2->null,返回 1->2->null

给出 1->1->2->3->3->null,返回 1->2->3->null

 

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param head: head is the head of the linked list
     * @return: head of linked list
     */
    ListNode * deleteDuplicates(ListNode * head) {
        // write your code here
        if(head==NULL)
            return 0;
        ListNode *p=head;
        ListNode *next;
        while(p->next!=NULL)
        {
            next=p->next;
            if(next->val==p->val)
            {
                p->next=next->next;
                delete(next);
            }else//else很重要
            {
                p=p->next;
            }
            
        }
        return head;
    }
};

 

LintCode 112. 删除排序链表中的重复元素

标签:lin   class   dup   lint   bsp   code   blog   null   turn   

原文地址:https://www.cnblogs.com/zslhg903/p/8367883.html

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