【编程题】删除单链表重复元素(Java实现)(Shopee笔试题)
题目来源
(Shopee笔试题)
题目描述
对一个单链表去重,如果链表中有重复的项则,删除第二项以及以后的项,需要对链表保持顺序。
输入描述:
输入:
带有重复项的单向链表
输出描述:
输出:
不含有重复项的单向链表
例如:
输入
1 2 3 7 2 1 3 3 9
输出
1 2 5 7 3 9
解答
方法一 输入元素固定时
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Main1{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
ListNode listNode=new ListNode(0);
ListNode head=listNode;
//int n=sc.nextInt();
for(int i=0;i<9;i++){//输入元素为9个时
head.next=new ListNode(sc.nextInt());
head=head.next;
}
deleteNode(listNode.next);
}
public static void deleteNode(ListNode head){
if(head==null||head.next==null)return ;
ListNode printNode=new ListNode(-1);
printNode.next=head;
ListNode pre =printNode;
ListNode currentNode= printNode.next;
HashMap<Integer,Integer>map=new HashMap<>();
while(pre!=null&&pre.next!=null){
if(map.containsKey(currentNode.val)){
pre.next=currentNode.next;
currentNode=currentNode.next;
}
else{
map.put(currentNode.val,1);
pre=currentNode;
currentNode=currentNode.next;
}
}
printNode=printNode.next;
while (printNode!=null){
System.out.println(printNode.val);
printNode=printNode.next;
}
}
}
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val=val;
}
}
方法一 输入元素不确定时
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Main4{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
ListNode listNode=new ListNode(0);
ListNode head=listNode;
//int n=sc.nextInt();
String[] numArrays=sc.nextLine().split(" ");
for(int i=0;i<numArrays.length;i++){
head.next=new ListNode(Integer.valueOf(numArrays[i]));
head=head.next;
}
deleteNode(listNode.next);
}
public static void deleteNode(ListNode head){
if(head==null||head.next==null)return ;
ListNode printNode=new ListNode(-1);
printNode.next=head;
ListNode pre =printNode;
ListNode currentNode= printNode.next;
HashMap<Integer,Integer>map=new HashMap<>();
while(pre!=null&&pre.next!=null){
if(map.containsKey(currentNode.val)){
pre.next=currentNode.next;
currentNode=currentNode.next;
}
else{
map.put(currentNode.val,1);
pre=currentNode;
currentNode=currentNode.next;
}
}
printNode=printNode.next;
while (printNode!=null){
System.out.println(printNode.val);
printNode=printNode.next;
}
}
}
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val=val;
}
}