重复的保留一个node
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public ListNode deleteDuplicates(ListNode head) { if(head == null){ return null; } ListNode newhead = new ListNode(-1, head); ListNode cur = head; ListNode before = newhead;
while(cur.next != null){ if(cur.val == cur.next.val){ before.next = cur.next; } else{ before = before.next; } cur = cur.next; }
return newhead.next; }
|
重复都删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public ListNode deleteDuplicates(ListNode head) { if(head == null){ return null; } ListNode newhead = new ListNode(-1, head); ListNode cur = head; ListNode before = newhead;
while(cur != null && cur.next != null){ if(cur.val == cur.next.val){ ListNode end = cur.next; while(cur.val == end.val){ if(end.next == null){ end = null; break; } else{ end = end.next; } } before.next = end; cur = end; } else{ before = before.next; cur = cur.next; } } return newhead.next; }
|
Author:
Sheng Wang
Permalink:
https://shengwang.fun/2022/11/28/nodelistdelrepeat/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE