题解 | #删除无序链表中值重复出现的节点#
import java.io.;
import java.util.;
class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}
//String数组转链表 非环 public static Node tranStringNoLoop(String[] nums){ Node head=new Node(Integer.parseInt(nums[0])); Node cur=head; for(int i=1;i<nums.length;i++){ cur.next=new Node(Integer.parseInt(nums[i])); cur=cur.next; } return head; } //int数组转链表 非环 public static Node tranIntegerNoLoop(int[] nums){ Node head=new Node(nums[0]); Node cur=head; for(int i=1;i<nums.length;i++){ cur.next=new Node(nums[i]); cur=cur.next; } return head; } //打印链表[非环] public static void printNodeList(Node head){ StringBuilder sb=new StringBuilder(); while (head!=null){ sb.append(head.value).append(" "); head=head.next; } System.out.println(sb.toString()); }
}
public class Main{
public static void remove(Node head){
if(head==null){
return;
}
HashSet<integer>set=new HashSet<integer>();
Node pre=head;
Node cur=head.next;
set.add(head.value);
while(cur!=null){
if(set.contains(cur.value)){
pre.next=cur.next;
}else{
set.add(cur.value);
pre =cur;
}
cur=cur.next;
}
}
public static void main(String[]args)throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
in.readLine();
String[] nums=in.readLine().split(" ");
Node head=Node.tranStringNoLoop(nums);
remove(head);
Node.printNodeList(head);
}
}</integer></integer>