Remove Duplicates from Sorted List II

来源:互联网 发布:浙江师范行知学院宿舍 编辑:程序博客网 时间:2024/05/20 13:16

Fair Remove Duplicates from Sorted List IIMy Submissions

28%
Accepted

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct numbers from the original list.

Example

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

KEY: 

1. use dummy node. Because the head of the original node might be changed.

2. every iteration we compare head.next.val with head.next.next.val. Save head.next.val if the the two adjacent nodes are equal. And use a while loop to delete all the nodes with the same value. The deletion starts from head.next.

</pre><pre name="code" class="java">
</pre><p></p><p><pre name="code" class="java">/** * Definition for ListNode * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    /**     * @param ListNode head is the head of the linked list     * @return: ListNode head of the linked list     */    public static ListNode deleteDuplicates(ListNode head) {        if (head == null || head.next == null) {            return head;        }        ListNode dummy = new ListNode(0);        dummy.next = head;        head = dummy;                while (head.next != null && head.next.next != null) {            if (head.next.val == head.next.next.val) {                int val = head.next.val;                while (head.next != null && head.next.val == val) {                    head.next = head.next.next;                }            } else {                head = head.next;            }        }        return dummy.next;    }}


0 0
原创粉丝点击