从链表的第一个节点开始遍历,如果当前的结点的值等于下一个结点的值,就说明这个结点是要删除的。然后看一下后面有多少个结点等于这个值,一起删除掉。
因为第一个结点也有可能被删除,所以在第一个结点前加一个头节点。
图中深色的部分需要删除
c++
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head == NULL){return head;} ListNode* front = new ListNode(-1); front->next = head; ListNode* now = front->next; ListNode* pre = front; ListNode* next = NULL; while(now!=NULL) { if(now->next!=NULL&& now->val == now->next->val) { ListNode* Dstart = pre; pre = now; now = now->next; while(now!=NULL&&now->val==pre->val) { delete pre; pre = now; now = now->next; } Dstart->next = now; pre = Dstart; continue; } pre = now; now = now->next; } return front->next; } };
java
import java.util.*; public class Solution { public ListNode deleteDuplicates (ListNode head) { if(head == null){return head;} ListNode front = new ListNode(-1); front.next = head; ListNode now = front.next; ListNode pre = front; ListNode next = null; while(now!=null) { if(now.next!=null && now.val == now.next.val) { ListNode Dstart = pre; pre = now; now = now.next; while(now!=null&&now.val==pre.val) { pre = now; now = now.next; } Dstart.next = now; pre = Dstart; continue; } pre = now; now = now.next; } return front.next; } }
python
class Solution: def deleteDuplicates(self , head ): if head == None: return head front = ListNode(-1) front.next = head now = front.next pre = front next = None while now!=None: if now.next!=None and now.val == now.next.val: Dstart = pre pre = now now = now.next while now!=None and now.val==pre.val: pre = now now = now.next Dstart.next = now pre = Dstart continue pre = now now = now.next return front.next