每日一题 为了工作 2020 0402 第三十一题

/**
* 问题:删除无序单链表中值重复出现的节点
*
* 给定一个无序单链表的头节点head, 删除其中值重复出现的节点。
* 例如: 1->2->3->3->4->4->2->1->1->null, 删除值重复的节点之后
* 为 1->2->3->4->null。
*
* 要求:
* 如果链表长度为 N, 时间复杂度达到 O(N)。
*
* 分析:
* 利用哈希表。时间复杂度为O(N), 额外空间复杂度为O(N)。
*
* 具体过程如下:
* 1.生成一个哈希表因为头节点是不用删除的节点所以首先将头节点的值放入哈希表。
* 2.从头节点的下一个节点开始往后遍历节点, 假设遍历到 cur节点,先检测cur的
* 值是否在哈希表中, 如果在, 则说明cur节点的值是之前出现过的, 就将 cur
* 节点删除,删除的方式是将最近一个没有被删除的节点 pre连接到 cur的下一个
* 节点, 即 pre.next = cur.next。如果不在,将 cur节点的值加入哈希表,
* 同时令 pre=cur, 即更新最近一个没有被删除的节点。
*
* @author 雪瞳
*
*/

*代码

public class Node {
	public int value;
	public Node next;
	public Node(int data){
		this.value=data;
	}
}

  

public class RemoveBothElements {

	public Node removeElements(Node head){
		
		if(head == null){
			return head;
		}
		
		HashSet<Integer> set = new HashSet<>();
		Node current = null;
		Node preCurrent = null;
		
		set.add(head.value);
		preCurrent=head;
		current=head.next;
		while(current!=null){
			if(set.contains(current.value)){
				preCurrent.next=current.next;
			}else{
				set.add(current.value);
				preCurrent=current;
			}
			current=current.next;
		}
		
		return head;
	}
}

  

import java.util.Random;
import java.util.Scanner;

public class TestRemoveBothElements {

	public static void main(String[] args) {
		TestRemoveBothElements test = new TestRemoveBothElements();
		RemoveBothElements remove = new RemoveBothElements();
		Scanner sc = new Scanner(System.in);
		System.out.println("输入链表长度");
		int len=0;
		len =sc.nextInt();
		Node head = test.getNodeList(len);
		test.showNodeList(head);
		Node result = remove.removeElements(head);
		test.showNodeList(result);
		sc.close();
	}
	public Node getNodeList(int length){
		Random rand = new Random();
		Node nodeArray[]= new Node[length];
		for(int i=0;i<length;i++){
			nodeArray[i]=new Node(rand.nextInt(10));
		}
		for(int i=0;i<length-1;i++){
			nodeArray[i].next = nodeArray[i+1];
		}
		return nodeArray[0];
	}
	public void showNodeList(Node head){
		Node current = null;
		current = head;
		System.out.println("链表元素如下...");
		while(current!=null){
			System.out.print(current.value+"	");
			current=current.next;
		}
		System.out.println();
	}
}

  

*运行结果

每日一题 为了工作 2020 0402  第三十一题