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

Posted zslhg903

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode 112. 删除排序链表中的重复元素相关的知识,希望对你有一定的参考价值。

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

 样例

给出 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. 删除排序链表中的重复元素的主要内容,如果未能解决你的问题,请参考以下文章