需求:
给定一个链表,将其中重复的节点删除,不保留重复的节点。
分析:
1、思路一
1)创建map集合,遍历链表节点,存储节点值和其出现的次数
2)遍历map集合,将其中出现次数是1的节点连起来,输出头结点
代码:
import java.util.*;
//链表节点类
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
this.next = null;
}
}
class DeleteListNode{
//创建链表,并返回头结点
public static ListNode getHead(int[] arr){
if(arr == null)
throw new IllegalArgumentException("illegal parameters");
if(arr.length == 0)
return null;
ListNode head = new ListNode(arr[0]);
ListNode p = head;
for(int i = 1; i < arr.length; i++){
p.next = new ListNode(arr[i]);
p = p.next;
}
return head;
}
//删除链表中的重复节点,不保留重复节点
public static ListNode deleteListNode(ListNode head){
if(head == null)
return null;
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
ListNode p = head;
//遍历节点,将各个节点的值和其出现次数存到map集合中
while(p != null){
int count = 0;
if(hm.containsKey(p.val))
count = hm.get(p.val);
hm.put(p.val, count+1);
p = p.next;
}
//遍历map集合,将其中出现次数是1的节点连起来返回
ListNode result = new ListNode(0);
p = result;
for(Map.Entry<Integer, Integer > me : hm.entrySet()){
if(me.getValue() == 1)
{
p.next = new ListNode(me.getKey());
p = p.next;
}
}
return result.next;
}
//输出链表
public static void printListNode(ListNode head){
if(head == null)
return;
while(head != null){
if(head.next != null)
System.out.print(head.val+"->");
else
System.out.println(head.val);
head = head.next;
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] arr = new int[scan.nextInt()];
for(int i = 0; i < arr.length; i++){
System.out.print("arr["+i+"] = ");
arr[i] = scan.nextInt();
}
ListNode head = getHead(arr);
System.out.println("链表:");
printListNode(head);
deleteListNode(head);
System.out.println("删除重复元素之后,链表:");
printListNode(deleteListNode(head));
}
}