2.2.5 Remove Duplicates from Sorted List II

来源:互联网 发布:check windows version 编辑:程序博客网 时间:2024/06/05 20:18
Link: https://oj.leetcode.com/problems/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.

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

我的思路:思路很简单。但是代码还是写的有问题。

Time: O(n), Space: O(1)

while嵌套一个while。 为什么?

我的初始代码:

public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head == null) return head;        ListNode pre = new ListNode(-1);        pre.next = head;        ListNode cur = head;        while(cur.next != null){            if(cur.next.val != cur.val){                pre.next = cur;                pre = cur;                cur = cur.next;            }            else{                cur = cur.next;            }        }        return head;    }}

正确代码:

public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head == null) return head;        ListNode dummy = new ListNode(-1);        dummy.next = head;        ListNode pre = dummy;        ListNode cur = head;        while(cur != null){            //find the place to change pointer            while(cur.next != null && cur.next.val == cur.val){                cur = cur.next;            }            if(pre.next == cur){                pre = pre.next;            }            else{                pre.next = cur.next;            }            cur = cur.next;        }        return dummy.next;    }}


相关题目: 注意这一题和Remove Duplicates in Sorted List的区别。

两道题可以用while嵌套while来做,上一道还可以用while嵌套if/else来做


0 0
原创粉丝点击