力扣:移除重复节点

该篇博客探讨了如何在不使用临时缓冲区的情况下,从无序链表中删除重复节点。提供了三种不同的解决方案,分别通过使用哈希集合、双指针法以及单一指针法实现。这些方法在保持链表元素顺序的同时,有效移除了重复的值,优化了链表结构。
面试题 02.01. 移除重复节点

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

示例1:

 输入:[1, 2, 3, 3, 2, 1]
 输出:[1, 2, 3]

示例2:

 输入:[1, 1, 1, 1, 2]
 输出:[1, 2]

提示:

  1. 链表长度在[0, 20000]范围内。
  2. 链表元素在[0, 20000]范围内。

进阶:

如果不得使用临时缓冲区,该怎么解决?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        HashSet<Integer> hash = new HashSet<>();
        ListNode root = null;
        ListNode recent = null;
        while(head!=null){
            if(!hash.contains(head.val)){
                if(root==null){
                    root = recent = head;    
                }  
                else{
                    recent.next = head;
                    recent = recent.next;
                }
                hash.add(head.val);
            }
            head = head.next;
            if(recent!=null)
                recent.next = null;
        }
        return root;
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        HashSet<Integer> hash = new HashSet<>();
        ListNode root = head;
        if(root == null)
            return null;
        hash.add(root.val);
        while(root.next!=null){
            if(hash.add(root.next.val))
                root = root.next;
            else
                root.next = root.next.next;

        }
        return head;
    }
}
进阶
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head==null)
            return null;
        ListNode root = head;
        while(root!=null){
            ListNode recent = root;
            while(recent.next!=null){
                if(root.val==recent.next.val)
                    recent.next = recent.next.next;
                else
                    recent = recent.next;
            }
            root = root.next;
        }
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XdpCs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值