题解 | #删除有序链表中重复的元素-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;
    }
}

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

相关推荐

葬爱~冷少:我当时都是上午刷力扣,下午背八股,有活给我先别急,没活就干自己的事情
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务