面试题 02.01. 移除重复节点
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
- 链表长度在[0, 20000]范围内。
- 链表元素在[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;
}
}
该篇博客探讨了如何在不使用临时缓冲区的情况下,从无序链表中删除重复节点。提供了三种不同的解决方案,分别通过使用哈希集合、双指针法以及单一指针法实现。这些方法在保持链表元素顺序的同时,有效移除了重复的值,优化了链表结构。
405

被折叠的 条评论
为什么被折叠?



