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

输入:链表 = 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 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

 

你可能感兴趣的:(数据结构,链表)