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

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

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

import java.util.*;

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

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if(head == null){ return head;}
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode cur = dummyNode;
        while (cur.next != null && cur.next.next != null) {
            if(cur.next.val == cur.next.next.val){
                int x = cur.next.val;
//                 给出的链表为1→2→3→3→4→4→5, 返回1→2→3→4→5.
//                 while(cur.next.next != null && cur.next.next.val == x){
//                     cur.next = cur.next.next;
//                 }
                // 给出的链表为1→2→3→3→4→4→5, 返回1→2→5.
                while(cur.next != null && cur.next.val == x){
                    cur.next = cur.next.next;
                }
            }else{
                cur = cur.next;
            }

        }
        return dummyNode.next;
    }
}
全部评论

相关推荐

04-25 19:29
已编辑
宁波大学 运营
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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