题目要求
1 2 3 4 5
|
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3.
|
将链表中重复的元素全部删除,返回新的头结点。
相比于Remove Duplicates from Sorted List I,这里将重复的元素全部删除。
想要了解Remove Duplicates from Sorted List I,请参考我的这篇博客
思路和代码
这里,我们首先需要一个伪头节点指向当前的头节点,以确保我们最后能够找到结果集的头节点。除此以外,我们还需要知道重复元素的前一个值和重复元素的最后一个值。
举个例子:如果数组元素为[1,2,2,3],那么我们需要知道1这个节点和3这个节点的位置,并将1的下一个节点指向3。特殊情况,如[1,1,2,2],这是我们就可以将伪头结点作为我们的前节点,并将2作为我们的后节点。如果存在重复值,则跳过重复值后,前节点不变,否则前节点跟随后节点同时向后移动。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 大专栏 leetcode82.Remove Duplicates from Sorted List II>15 16 17 18 19 20 21 22 23 24 25 26 27
|
public ListNode (ListNode head) { if(head==null || head.next==null){ return head; } ListNode start = new ListNode(0); start.next = head; ListNode prevNode = start; ListNode current = head; while(current != null){ if(current.next != null && current.val == current.next.val){ do{ current = current.next; }while(current.next != null && current.val == current.next.val); prevNode.next = current.next; }else{ prevNode = current; } current = current.next; } return start.next; }
public class { int val; ListNode next; ListNode(int x) { val = x;} }
|