LeetCode/83. Remove Duplicates from Sorted List.md

35 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)
# 思路
去除链表中的重复元素。
设置两个相邻的指针pre和ppre代表已处理部分的最后一个节点p代表待处理节点比较pre和p的值来决定是否删除p
# 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;
}
};
```