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

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

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

public class Solution {
    /**
     * 删除有序链表中的重复元素
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode current = head;
        while (current != null && current.next != null) {
            if (current.val == current.next.val) {
                current.next = current.next.next; // 删除重复的节点
            } else {
                current = current.next; // 移动到下一个节点
            }
        }
        return head;
    }

    /**
     * 根据数组创建链表
     * @param values 整数值数组
     * @return 链表头节点
     */
    public ListNode DefaultListNode(Integer[] values) {
        if (values == null || values.length == 0) {
            return null;
        }

        ListNode head = new ListNode(values[0]);
        ListNode current = head;
        for (int i = 1; i < values.length; i++) {
            current.next = new ListNode(values[i]);
            current = current.next;
        }
        return head;
    }

    
}
  1. 集合.toArray(new Integer[0])
  2. Arrays.sort(数组);

public ListNode deleteDuplicates1(ListNode head) {
        ListNode temp = head;

        while (temp != null && temp.next != null) {

            if (temp.next != null && temp.val == temp.next.val) {
                temp.next = temp.next.next;
            } else {
                temp = temp.next;
            }
        }
        return head;
    }

1. 删除代码是pre.next=pre.next.next。

2. 通过一个指针拿到自己指向和下一个指向对比。有一样就继续对比。没有的话就是继续走。

全部评论

相关推荐

zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
码农索隆:力扣的题目还挺贴近现实
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 15:37
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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