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

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

https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79

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
        ListNode cur = head;
        //遍历链表
        while(cur!=null&&cur.next!=null){
            ListNode next = cur.next;
            //将所有重复的元素删除
            while(cur.val==next.val&&next!=null&&next.next!=null){
                //这里可能会溢出,所以上述条件加上next.next!=null
                cur.next = next.next;
                next = cur.next;
            }
            //将有可能漏掉的元素删除
            if(cur.next!=null){
                if(cur.val==cur.next.val){
                    cur.next = null;
                }
            }
            //指针往后移
            cur = cur.next;
        }
        
        return head;
    }
}

#数据结构编程链表#
全部评论

相关推荐

06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
牛客38347925...:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:30
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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