数据结构 从未排序的链表中删除重复项

该代码示例展示了一个Java程序,它使用哈希集合来遍历无序链表并删除所有重复的节点。程序首先创建一个哈希集用于存储已访问的值,然后逐个检查链表中的节点。如果节点值在哈希集中存在,则删除该节点;否则,将值添加到哈希集并移动到下一个节点。最后,程序打印处理后的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入:链表 = 12->11->12->21->41->43->21 输出:12->11->21->41
->43。
解释: 第二次出现 o 12 和 21 被删除

输入:链表 = 12->11->12->21->41->43->21 输出:12->11->21->41
->43。

使用哈希从未排序的链表中删除重复项:

遍历链接列表。对于每个新遇到的元素,检查它是否在哈希表中:如果是,我们将其删除;否则将其放在哈希表中。

请按照以下步骤实施该想法:

  • 创建无序集以跟踪访问的元素。
  • 从头节点遍历链表到结束节点
    • 如果当前节点已存在于哈希集中。然后删除当前节点 
    • 否则移动插入哈希集中的节点并移动到下一个节点。
  • 返回

 

// Java program to remove duplicates
// from unsorted linkedlist

import java.util.HashSet;

public class removeDuplicates {
	static class node {
		int val;
		node next;

		public node(int val) { this.val = val; }
	}

	/* Function to remove duplicates from a
	unsorted linked list */
	static void removeDuplicate(node head)
	{
		// Hash to store seen values
		HashSet<Integer> hs = new HashSet<>();

		/* Pick elements one by one */
		node current = head;
		node prev = null;
		while (current != null) {
			int curval = current.val;

			// If current value is seen before
			if (hs.contains(curval)) {
				prev.next = current.next;
			}
			else {
				hs.add(curval);
				prev = current;
			}
			current = current.next;
		}
	}

	/* Function to print nodes in a given linked list */
	static void printList(node head)
	{
		while (head != null) {
			System.out.print(head.val + " ");
			head = head.next;
		}
	}

	public static void main(String[] args)
	{
		/* The constructed linked list is:
		10->12->11->11->12->11->10*/
		node start = new node(10);
		start.next = new node(12);
		start.next.next = new node(11);
		start.next.next.next = new node(11);
		start.next.next.next.next = new node(12);
		start.next.next.next.next.next = new node(11);
		start.next.next.next.next.next.next = new node(10);

		System.out.println(
			"Linked list before removing duplicates :");
		printList(start);

		removeDuplicate(start);

		System.out.println(
			"\nLinked list after removing duplicates :");
		printList(start);
	}
}

// This code is contributed by Rishabh Mahrsee

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值