在Java中删除链表中的重复项可以通过以下步骤来实现:
以下是一种可能的实现示例:
import java.util.HashSet;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Main {
public static ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
HashSet<Integer> set = new HashSet<>();
ListNode current = head;
ListNode prev = null;
while (current != null) {
if (set.contains(current.val)) {
prev.next = current.next;
} else {
set.add(current.val);
prev = current;
}
current = current.next;
}
return head;
}
public static void main(String[] args) {
// 创建一个有重复项的链表: 1 -> 2 -> 2 -> 3 -> 3 -> 4
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(3);
head.next.next.next.next = new ListNode(3);
head.next.next.next.next.next = new ListNode(4);
// 删除重复项
head = deleteDuplicates(head);
// 输出结果:1 -> 2 -> 3 -> 4
ListNode current = head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("null");
}
}
这个算法的时间复杂度为O(n),其中n是链表的长度。
领取专属 10元无门槛券
手把手带您无忧上云