• [Leetcode] Remove duplicates from sorted list 从已排序的链表中删除重复元素


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

    For example,
    Given1->1->2, return1->2.
    Given1->1->2->3->3, return1->2->3.

    思路:遍历链表。比较相邻的结点,若是有相等的情况,则cur不动,而将其后继从其next变为next->next;没有,则正常遍历就行。

     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 NULL;  //return head也可以
    14         ListNode *cur=head;
    15         while(cur->next)
    16         {
    17             if(cur->val==cur->next->val)
    18                 cur->next=cur->next->next;
    19             else
    20                 cur=cur->next;
    21         } 
    22         return head;   
    23     }
    24 };
  • 相关阅读:
    jchdl
    jchdl
    jchdl
    jchdl
    jchdl
    jchdl
    jchdl
    UVa 437 (变形的LIS) The Tower of Babylon
    UVa 1025 (动态规划) A Spy in the Metro
    UVa 10129 (并查集 + 欧拉路径) Play on Words
  • 原文地址:https://www.cnblogs.com/love-yh/p/7007221.html
Copyright © 2020-2023  润新知