[LeetCode] 83. Remove Duplicates from Sorted List
1. 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/
2. 解题思路
- 删除链表节点会涉及到两个指针:prev指针和cur指针
3. 算法
- prev指针和cur指针分别指向前两个节点
- 从cur指向的节点开始循环遍历,当prev和cur的val相同时,将prev指向cur->next节点;否则prev指向cur的节点
4. 实现
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 *prev = head;
for(ListNode *cur = prev->next; cur != NULL; cur = cur->next){
if(prev->val == cur->val){
prev->next = cur->next;
}else{
prev = cur;
}
}
return head;
}
};