Remove Duplicates from Sorted List II

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.

思路:

  prepre pre cur 指针的相互作用

我的代码:

public class Solution {

    public ListNode deleteDuplicates(ListNode head) {

        if(head == null || head.next == null)   return head;

        ListNode dummy = new ListNode(-1);

        dummy.next = head;

        ListNode prepre = dummy;

        ListNode pre = head;

        ListNode cur = head.next;

        while(cur != null)

        {

            if(cur.val == pre.val)

            {

                while(cur != null && cur.val == pre.val)

                {

                    cur = cur.next;

                }

                prepre.next = cur;

                pre = cur;

                if(cur != null)

                    cur = cur.next;

                else

                    cur = null;

            }

            else

            {

                prepre = pre;

                pre = cur;

                cur = cur.next;

            }

        }

        return dummy.next;

    }

}
View Code

学习之处:

  • 这种问题无非是用两个指针标示前后位置或者三个指针标示,标示好了位置前后关系后,再画画图就差不多了。
  • 当然别人也可以通过不用标志位置前后关系,也能做出来,如Remove Duplicates from Sorted List ,有人写出了这样简洁的代码,通过动还是不动的方法,简洁明了。
public class Solution {

    public ListNode deleteDuplicates(ListNode head) {

        if (head == null) {

            return null;

        }



        ListNode node = head;

        while (node.next != null) {

            if (node.val == node.next.val) {

                node.next = node.next.next;

            } else {

                node = node.next;

            }

        }

        return head;

    }

}
View Code

 

你可能感兴趣的:(remove)