一:解题思路
Time:O(n),Space:O(1)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* prev = dummy; ListNode* cur = prev->next; while (cur!=NULL) { while (cur->next != NULL && cur->val == cur->next->val) cur = cur->next; if (prev->next != cur) prev->next = cur->next; else prev = prev->next; cur = prev->next; } return dummy->next; } };
Java:
class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode dummy=new ListNode(0); dummy.next=head; ListNode prev=dummy; ListNode cur=prev.next; while (cur!=null) { while (cur.next!=null && cur.val==cur.next.val) cur=cur.next; if(prev.next!=cur) prev.next=cur.next; else prev=prev.next; cur=prev.next; } return dummy.next; } }
原文地址:https://www.cnblogs.com/repinkply/p/12663146.html
时间: 2024-10-26 12:51:52