题目:给定一个无顺序单链表的头节点head,删除其中值重复的元素
思路:利用哈希表。
生成一个哈希表,因为头节点是没有必要去删除的节点,所以首先将头节点放入哈希表;
从头结点的下一个节点开始往后遍历节点,如果当前cur指向的节点的值与哈希表中存在的节点值相同,测删除该节点,将最近没有删除的节点的地址与删除节点的下一个节点
的地址连接起来(pre->next = cur->next);如果与哈希表中的节点不存在值相等的condition,将cur的节点放入哈希表中,即pre = cur;
废话不说,看代码:
package com.ly; import java.util.HashSet; public class removeRepl { public static void main(String[] args){ Node a = new Node(1 ,"1"); Node b = new Node(2,"2"); a.next = b; Node c = new Node(2,"3"); b.next = c; Node d = new Node(3,"4"); c.next = d; Node e = new Node(3,"5"); d.next = e; System.out.println(func(a)); } public static Node func(Node head){ if(head == null){ return null; } 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; } return head; } }
运行结果:
标签:Node,head,cur,--,next,链表,new,节点 From: https://www.cnblogs.com/99kol/p/16989887.html