Daily work entitled 20,200,402 thirty questions

/ **
* Question: delete the node value of a single recurring disorder linked list
*
* Given an unordered list head single head node, deleting the node of which the value is repeated.
* For example: After 1-> 2-> 3-> 3-> 4-> 4-> 2-> 1-> 1-> null, delete duplicate node values
* 1-> 2-> 3-> 4 -> null.
*
* Requirements:
* If the chain length is N, the time complexity reaches O (N).
*
* Analysis:
* use a hash table. Time complexity is O (N), the additional space complexity is O (N).
*
* Procedure is as follows:
* 1. Generate a hash table because the first node is the first node without deleting So put the value of the head node of the hash table.
* 2. Start the next node of the head node to traverse next node, assuming cur traversed node, the first detected cur
* value is in the hash table, if so, the value of cur nodes described before had appeared, it the cur
* delete nodes, deleted way is to connect a recently deleted without pre node to the next cur
* node, i.e. pre.next = cur.next. If not, the value added to a hash table cur node
* at the same time make pre = cur, that is a recently updated node has not been deleted.
*
* @Author snow pupil
*
* /

* Code

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+"\t");
			current=current.next;
		}
		System.out.println();
	}
}

  

*运行结果

 

 

Guess you like

Origin www.cnblogs.com/walxt/p/12618942.html