LeetCode/solutions/83. Remove Duplicates from Sorted List.md

35 lines
1.1 KiB
Markdown
Raw Permalink Normal View History

# [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)
# 思路
去除链表中的重复元素。
设置两个相邻的指针pre和ppre代表已处理部分的最后一个节点p代表待处理节点比较pre和p的值来决定是否删除p
# C++
2019-09-13 15:08:41 +00:00
``` C++
/**
* 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 head;
ListNode *pre = head, *p = head -> next, *dup; // dup是待删除的重复节点
while(p){
while(p !=NULL && p -> val == pre -> val){ // 若p的值等于pre的值
pre -> next = p -> next; // 指针跳过p
dup = p;
dup -> next = NULL;
delete dup;
p = pre -> next; // p指针后移
}
pre = p; // pre后移
if(p) p = p -> next;
}
return head;
}
};
```