• LeetCode:Remove Duplicates from Sorted List


    Problem:

    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.

    Solution:同Remove Duplicates from Sorted Array的思路一样,每次用结果链表的尾指针pre与遍历原链表的指针last的val作比较,不同则加入原链表。最后返回结果,注意每次加入

    结果链表中,pre->next=NULL。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* deleteDuplicates(ListNode* head) {
    12         
    13         if(head==NULL) return head;
    14         ListNode *dummy=new ListNode(-1);
    15         
    16         ListNode *pre=head;
    17         ListNode *last=head->next;
    18         
    19         dummy->next=pre;
    20         pre->next=NULL;
    21         
    22         while(last!=NULL)
    23         {
    24             if(pre->val!=last->val)
    25             {
    26                 pre->next=last;
    27                 pre=pre->next;
    28                 last=last->next;
    29                 pre->next=NULL;
    30             }
    31             else
    32                 last=last->next;
    33             
    34         }
    35         return dummy->next;
    36         
    37     }
    38 };
  • 相关阅读:
    Python解释器【转载】
    Python第一行代码
    Hive安装部署
    Python 3.6安装教程
    Spark安装部署
    Code:Blocks中文输出乱码解决方法
    HBase集群安装部署
    Hadoop集群时间同步
    ZooKeeper安装部署
    Linux重置mysql密码
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4651793.html
Copyright © 2020-2023  润新知