mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
35 lines
1.1 KiB
Markdown
35 lines
1.1 KiB
Markdown
![]() |
# [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)
|
|||
|
# 思路
|
|||
|
去除链表中的重复元素。
|
|||
|
设置两个相邻的指针pre和p,pre代表已处理部分的最后一个节点,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;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|