题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024


/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        ListNode head1 = new ListNode(0);
        head1.next = head;
        ListNode pre = head1;
        ListNode cur = head;
        if(head == null || head.next == null){
            return head;
        }
        int count = 0;
        while(cur != null && cur.next != null){
            if(cur.val == cur.next.val){
                cur.next = cur.next.next;
                count++;
            }else{
                if(count >0){
                    pre.next = cur.next;//可移动
                    count = 0;
                }
                else{
                    pre = cur;//关键
                }
                cur = cur.next;//关键
            }
        }
        if(count > 0){//关键
            pre.next = cur.next;
        }
        return head1.next;
    }
}












全部评论

相关推荐

牛客78682892...:直接点还好,总比要了简历也不回的强
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务