码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates From Sorted List II

时间:2016-01-24 08:09:34      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

First we need to get the head node, use a boolean value to mark whether we find a new head or not. When we traverse the linked list, 

if(cur.val != cur.next.val && flag){
newHead = cur;
flag = false;
}

Once we find the first non-duplicative node, set that node to be head, and flag is false, meaning that we already find the head node, no need to find a new head anymore.

 

Use a pointer to record the previous node that ahead of the duplicative nodes, use the while loop

while(cur != null && cur.next != null && cur.val == cur.next.val) cur = cur.next;

to get the last node of the duplicative nodes. Then the cur = cur.next; can find the first node after the duplicative nodes, let prev.next = cur.

 

after the while loop, we need to check whether we already find a new head. If not, set the current node(maybe null) to be the head.

 

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode cur = head;
        ListNode prev = head;
        ListNode newHead = head;
        boolean flag = true;
        while(cur != null && cur.next != null){
            if(cur.val != cur.next.val && flag){
                newHead = cur;
                flag = false;
            }
            if(cur.val != cur.next.val) prev = cur;
            while(cur != null && cur.next != null && cur.val == cur.next.val) cur = cur.next;
            cur = cur.next;
            prev.next = cur;
        }
        if(flag) return cur;
        return newHead;
    }
}

 

Remove Duplicates From Sorted List II

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5154512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!