LeetCode83 Remove Duplicates from Sorted List

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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

样例

1
2
3
4
Input:
1->1->2
Output:
1->2
1
2
3
4
Input:
1->1->2->3->3
Output:
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
/**
* 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) {
int preVal = INT_MAX;
ListNode *cur = head, *pre = head;
while (cur != NULL) {
if (cur->val == preVal) pre->next = cur->next;
else pre = cur;
preVal = cur->val;
cur = cur->next;
}
return head;
}
};
分享到 评论