/**
* 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 NULL;
ListNode* now = head;
while(now->next!=NULL){
if(now->val == now->next->val){
ListNode* temp = now->next;
now->next = now->next->next;
delete temp;
}else{
now = now->next;
}
}
return head;
}
};
No.132 - LeetCode83 - 删除重复节点
本文介绍了一种在单链表中删除所有重复元素的方法。通过遍历链表,比较当前节点与下一个节点的值,若相同则跳过并删除下一个节点,直至链表末尾。该算法能有效移除链表中所有重复的数值。

被折叠的 条评论
为什么被折叠?



