美文网首页
Remove Duplicates from Sorted Li

Remove Duplicates from Sorted Li

作者: 极速魔法 | 来源:发表于2017-06-25 19:06 被阅读7次

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    For example,
    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.

    class Solution {
        //83. Remove Duplicates from Sorted List
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(head==NULL){
                return NULL;
            }
            ListNode* p=head;
            ListNode* q=head->next;
    
            if(q == NULL){
                //may head only
                return head;
            }
            while(q !=NULL){
                if(p->val==q->val){
                    //two pointers p,q
                    //p q
                    //1,2,2,3
                    ListNode* delNode=q;
                    q=q->next;
                    delete delNode;
                    p->next=q;
    
                } else{
                    q=q->next;
                    p=p->next;
                }
            }
            return head;
        }
    };
    
    

    相关文章

      网友评论

          本文标题:Remove Duplicates from Sorted Li

          本文链接:https://www.haomeiwen.com/subject/qwyrcxtx.html