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

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

样例

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

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

分析:先开始的时候是想着head 和head->next作为基准 但其实pre和cur更合适

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode *deleteDuplicates(ListNode *head) {
        // write your code here
        if(head==NULL)
        return 0;
        if(head->next==NULL)
        return head;
        ListNode *cur=head;
        ListNode *pre=NULL;
        while(cur!=NULL)
        {
            
            if(pre!=NULL&&pre->val==cur->val)
            { 
                pre->next=cur->next;
                cur=pre->next;
            }
            else
            {
                pre=cur;
                cur=pre->next;
            }
        } 
        return head;
    }
};

  

原文地址:https://www.cnblogs.com/lelelelele/p/6111668.html