题干如下:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
与I版那道题不同之处是要把所有重复项都删除而不是留下一个,由于链表前几项有可能重复,删除后链表头结点会变,所以要新建一个节点,思路如下:
1.如果链表空或只有一项,返回原链表。
2.新建一个newHead节点下一个指向head,然后遍历,当前节点值与下一个节点值相同则删除下一个节点(这里跟I版相同),直到不相同时,把当前节点再删掉。
具体看代码
public ListNode deleteDuplicates(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode currNode = newHead;
while(currNode.next != null && currNode.next.next != null){
if(currNode.next.next.val == currNode.next.val){
while(currNode.next.next != null && currNode.next.next.val == currNode.next.val){
currNode.next.next = currNode.next.next.next;
}
currNode.next = currNode.next.next;
}else currNode = currNode.next;
}
return newHead.next;
}
其实与I版那道题比较,循环体里稍做了些改变,不是用currNode与currNode.next比较,而是currNode.next与currNode.next.next比较。