[Sword refers to offer] Delete duplicate nodes in a linked list __leetcode

Source: Internet
Author: User
/* struct ListNode {int val;
    struct ListNode *next;
ListNode (int x): Val (x), Next (NULL) {}}; * *: Class Solution {public:listnode* deleteduplication (listnode* phead) {ListNode *dummy=new ListNode (-1);
        Set an extra head node ListNode *cur=phead, *pre=dummy;
        dummy->next=phead;
                while (Cur&&cur->next) {if (cur->val==cur->next->val)//If there is a duplicate node {
                int val=cur->val;
                while (Cur&&cur->val==val) cur=cur->next;
                pre->next=cur;//the previous node to the next node of the repeating node} else {pre=cur;
            cur=cur->next;
    } return dummy->next;
}
};
		My Code: Class Solution {public:listnode* deleteduplication (listnode* phead) {if (phead==null) return NULL;
        if (Null==phead->next) return phead; ListNode *ans=phead, *NXT, *pre=null;//pre before a repeating node, NXT with the current nodeDuplicate next node while (Phead) {nxt=phead;
            BOOL Flag=false; while (Nxt->next&&nxt->next->val==phead->val)//Find duplicate last node {Nxt=nxt->ne
                xt
            Flag=true;
                } if (flag)//If there is a duplicate node {if (Null==pre) ans=nxt->next;
            else pre->next=nxt->next;
            else Pre=phead;
        phead=nxt->next;
    return ans; }
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.