删除重复值的结点

删除重复值的结点

问题重述:

给定一个无序单链表的头节点head,删除其中值重复出现的结点

问题分析:

这道题要删除重复值的结点,我们可以想到哈希表,因为哈希表是无序不重复的,我们使用哈希表对值进行保存,后续加入的值如果已经在哈希表中存在了,就删除,否则就加入哈希表

解法:

哈希表,或者多次遍历

解题:

代码:
public static Node deleteRepeatNode1(Node head) {
		if(head == null) {
			return head;
		}
		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;
	}
	public static Node deleteRepeatNode2(Node head) {
		if(head == null) {
			return head;
		}
		Node pre = null;
		Node cur = head;
		Node next = null;
		while(cur != null) {
			pre = cur;
			next = cur.next;
			while(next != null) {
				if(cur.value == next.value) {
					pre.next = next.next;
				}else {
					pre = next;
				}
				next = next.next;
			}
			cur = cur.next;
		}
		return null;
	}

总结:

遇见重复的问题,我们就可以考虑使用哈希表

posted @   foldn  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示