zoukankan      html  css  js  c++  java
  • [LeetCode] Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

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

    Hide Tags
     Linked List
    Have you met this question in a real interview? 
    Yes
     
    No
     

    Discuss

     

    思路:和Remove Duplicates from Sorted List一样,双指针,head指向要插入node的前一个node,p指向当前处理的node。

    如何判断是否重复呢,判断p和p->next是否一样,若一样,则不插入,不一样就要插入,但是这里忽略了NULL的处理,如果p->next== NULL,要单独处理。。

    另外,在找到p->val == p->next->val 时,要找打下一个p,不等于之前的val。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
        public:
            ListNode *deleteDuplicates(ListNode *head) {
                if(head == NULL)
                    return NULL;
    
                ListNode * p = head;
                ListNode dummy(-1);
                head = &dummy;
    
                while(p)
                {   
                    if(p->next == NULL || p->val != p->next->val)
                    {   
                        head->next = p;
                        head = p;
                        p = p->next;
                        // to break old link
                        head->next = NULL;
                    }   
                    else
                    {   
                        //find the node which its value is not equla to p->val
                        // and store the node as new p;
                        p = p->next;
                        while(p)
                        {   
                            if(p->next == NULL)
                            {   
                                //should end
                                head->next = NULL;
                                p = NULL;// jump the outer loop
                                break;// jump the inner loop
                            }
    
                            if(p->val != p->next->val)
                            {
                                p = p->next;
                                break;
                            }
                            else
                                p = p->next;
                        }
                    }
    
                    #if 0
                    cout << "p->val	" << p->val << endl;
                    cout << "head->val	" << head->val << endl;
                    #endif
                }
                return dummy.next;
            }
    };
  • 相关阅读:
    获取css信息
    html嵌套规则
    js获取ip地址
    match excel test search replace 用法
    js 宽和高
    判断类型 从零开始系列
    js随机数 从头开始系列
    苹果自带拼音转换方法
    iOS GCD 拾遗
    iOS用户响应者链的那些事儿
  • 原文地址:https://www.cnblogs.com/diegodu/p/4347583.html
Copyright © 2011-2022 走看看