题解 | #删除有序链表中重复的元素-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 null;
        ListNode res=new ListNode(-1);
        ListNode cur=res; 
        res.next=head; 
          while(cur.next != null && cur.next.next != null){//两个以上结点
            //遇到相邻两个节点值相同
            if(cur.next.val == cur.next.next.val){
                int temp = cur.next.val;//保存相同的结点值
                //将所有相同的都跳过
                while (cur.next != null && cur.next.val == temp)//只要等于相同的节点值,就跳过
                    cur.next = cur.next.next;
            }
            else
                cur = cur.next;
        }
        //返回时去掉表头
        return res.next;
        
    }
}
全部评论

相关推荐

05-12 22:16
已编辑
北京邮电大学 研发工程师
牛客302360988号:0offer+1 滴滴都不给我面 佬没投鹅吗,鹅应该很喜欢北邮吧
投递美团等公司6个岗位
点赞 评论 收藏
分享
HaxyBT:那我提前下班总可以了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务