Create 83. Remove Duplicates from Sorted List.md

This commit is contained in:
唐树森 2018-09-19 19:23:05 +08:00 committed by GitHub
parent b4c62b1273
commit 7427f21362
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,34 @@
# [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;
}
};
```