题解 | #删除有序链表中重复的元素-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
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null) {
            if (fast.val != slow.val) {
                slow = fast;
            } else {
                slow.next = fast.next;
            }
            fast = fast.next;
        }
        
        return head;
    }


    public ListNode deleteDuplicates2 (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        Set<Integer> set = new HashSet<>();
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        ListNode cur = head;
        while (cur != null) {
            if (!set.contains(cur.val)) {
                tail.next = cur;
                tail = cur;
                set.add(cur.val);
            }
            cur = cur.next;
        }
        tail.next = null;
        return dummy.next;
    }



}

全部评论

相关推荐

2025-11-26 09:37
山西大学 测试工程师
累死的一条狗:学长你电脑闹鬼了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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