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