leetCode 83. Remove Duplicates from Sorted List 链表

删除有序链表重复元素

83. Remove Duplicates from Sorted List

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.

题目大意:

去除有序链表内部相同元素,即相同元素只保留一个。


代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
  * 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->next;
         ListNode* pre = head;
         int  cur = head->val;
         while (p != NULL)
         {
             
             if (cur == p->val)
             {
                 pre->next = p->next;
             }
             else
             {
                 cur = p->val;
                 pre = p;
             }
             p = p->next;
         }
         return  head;
     }
};

其他简洁做法:

1.双while

参考自:https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing


1
2
3
4
5
6
7
8
9
10
11
12
class  Solution {
public :
     ListNode *deleteDuplicates(ListNode *head) {
         ListNode* cur = head;
         while  (cur) {
             while  (cur->next && cur->val == cur->next->val)
                 cur->next = cur->next->next;
             cur = cur->next;
         }
         return  head;
     }
};

2.双指针

参考自:https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing

1
2
3
4
5
6
7
8
9
10
11
12
ListNode *deleteDuplicates(ListNode *head) {
     ListNode*cur=head,*tail=head;
     while (cur){
         if (cur->val!=tail->val){
             tail->next=cur;
             tail=cur;
         }
         cur=cur->next;
         tail->next=NULL;
     }
     return  head;
}




本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837260
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值