zoukankan      html  css  js  c++  java
  • 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.

    这道题特别简单,其实关于链表的题都没有什么技巧,就是一堆的指针指来指去.

    /**
     * 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) {
           ListNode *pre,*now,*Head;
            if(!head||!head->next)return head;
            Head=new ListNode(-1);
            Head->next=head;
            pre=Head;
            now=head;
            while(now&&now->next)
            {
                if(now->val == now->next->val)
                {
                    while(now->next && now->val == now->next->val)
                    {
                        now=now->next;
                    }
                    pre->next=now->next;
                    now=now->next;
                }
                else 
                {
                    pre=now;
                    now=now->next;
                }
            }
            head=Head->next;
            delete(Head);
            return head;
        }
    };

      

  • 相关阅读:
    自定义转化
    asp.net JSON(一)
    做一个会偷懒的码农
    活动和监视器
    linq 分组求和
    sql语句查询列的说明
    chartControl
    LayOutControl
    sql 给表结构增加说明
    我的单件模式
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4775306.html
Copyright © 2011-2022 走看看