struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
//just record the previous pointer, and the current pointer
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* prev = NULL;
ListNode* cur = head;
while (cur)
{
if(!prev) prev = cur;
else if(cur->val != prev->val)
{
prev->next = cur;
prev = cur;
}
cur = cur->next;
}
if(prev) prev->next = NULL;
return head;
}
};
second time
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL) return head;
ListNode* prev = head;
ListNode* cur = head->next;
while(cur != NULL)
{
if(prev->val != cur->val)
{
prev->next = cur;//... need release memory?
prev = prev->next;
}
cur = cur->next;
}
prev->next = NULL;
return head;
}
};
本文提供了一种使用C++实现的高效方法来移除单链表中的连续重复元素。通过迭代方式,仅保留不重复的节点,从而简化链表结构。此算法避免了额外的空间开销,易于理解和实现。
727

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



