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;
    }
};

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM