Top 150 Questions - 2.1

2.1 Write code to remove duplicates from an unsorted linked list. FOLLOW UP: How would you solve this problem if a temporary buffer is not allowed?

RemoveDuplicate1()使用了Java的Hashtable,如果发现了duplicate,直接修改前继的next。

RemoveDuplicate2()没有使用buffer,方法类似1.3。

package Question2_1;

import java.util.Hashtable;


public class Question2_1<AnyType>
{
	public static void main(String[] args)
	{
		Question2_1<Integer> q = new Question2_1<Integer>();
		
		q.AddToList(4);q.AddToList(5);q.AddToList(6);q.AddToList(7);
		q.AddToList(1);q.AddToList(0);q.AddToList(1);q.AddToList(8);
		q.AddToList(3);q.AddToList(2);q.AddToList(5);q.AddToList(4);
		q.PrintList();
		q.RemoveDuplicate2();
		q.PrintList();
	}
	
	
	
	private Node<AnyType> head;
	public Question2_1()
	{
		// Initialize head to be an empty node
		head = new Node<AnyType>(null, null);
	}
	
	public void AddToList(AnyType e)
	{
		Node<AnyType> temp = head;
		while (temp.next != null)
			temp = temp.next;
		
		temp.next = new Node<AnyType>(e, null);
	}
	
	public void RemoveDuplicate1()
	{
		Hashtable<AnyType, Boolean> hashtable = new Hashtable<AnyType, Boolean>();
		Node<AnyType> pre = head;
		Node<AnyType> cur = head.next;
		
		while (cur != null)
		{
			// If find a duplicate, bypass current node
			if (hashtable.containsKey(cur.data))
				pre.next = cur.next;
			else
			{
			// If no duplicate, add current node data to hash table, and then modify pointer
				hashtable.put(cur.data, true);
				pre = cur;
			}
			
			cur = cur.next;
		}
	}
	
	public void RemoveDuplicate2()
	{
		Node<AnyType> pre = head;
		Node<AnyType> cur = head.next;
		
		while (cur != null)
		{
			// Use a temporary Node to iterate all prior nodes
			Node<AnyType> temp = head;
			for (; temp.next != cur; temp = temp.next)
				if (temp.data == cur.data)
					break;
			
			// If temp.next doesn't equal to cur; then we find a duplicate, bypass current node
			if (temp.next != cur)
				pre.next = cur.next;
			else
				pre = cur;
			
			cur = cur.next;
		}
	}
	
	public void PrintList()
	{
		Node<AnyType> temp = head;
		while (temp.next != null)
		{
			temp = temp.next;
			System.out.print(temp.data + " ");
		}
		
		System.out.println();
	}
	
	private class Node<Type>
	{
		Node(Type d, Node<Type> n)
		{
			data = d;
			next = n;
		}
		
		Type data;
		Node<Type> next;
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值