82. Remove Duplicates from Sorted List II

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

题目

与83. Remove Duplicates from Sorted List又不同,这次是删除有序链表的重复元素,一个不剩。
同样的,链表有序,意味着重复元素都挨着,但是要删除重复的所有元素,所以可以换一种方式解决,即新建一个头结点,只连接不重复的元素,重复的则跳过去。依照这个想法,代码如下:

代码

public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
         ListNode newhead = new ListNode(-1);//设置虚拟头结点
         ListNode tmp = newhead;//游标指针
         while(head != null && head.next != null){
                if (head.val == head.next.val){//head开始向后移动,当它和其下一个节点相同时
                    while(head.next != null && head.val == head.next.val){//让head不断后移
                        head = head.next;
                    }//此时head指向重复元素的最后一个,所以
                    head = head.next;//head需要再往后走一步
                }
                else{//当它与后面元素不相等时,则让tmp.next指向该元素,这里分析一下tmp:
                     //初始阶段,tmp=newhead,执行完 tmp.next = head后,此时newhead.next=head了
                     //tmp后移,而此时newhead不变。随着循环继续,newhead后面的值会由tmp更新,
                     //所以tmp作用就是用来维护以newhead为虚拟头结点的链表。
                    tmp.next = head;
                    tmp = tmp.next;
                    head = head.next;
                }
            }
         tmp.next = head;
        return newhead.next;
    }

你可能感兴趣的:(82. Remove Duplicates from Sorted List II)