[程序员代码面试指南]链表问题-删除无序链表中重复出现的节点

题意

如题

题解

使用HashSet。
时间复杂度O(n),额外空间复杂度O(n)。

todo

使用选择排序也可以做。

代码

import java.util.HashSet;

public class Main {
	public static void main(String args[]) {
		//测试
		Node n1=new Node(2);
		Node n2=new Node(2);
		Node n3=new Node(3);
		n1.next=n2;
		n2.next=n3;
		Node head=n1;
		
		rmRepeat(head);
		
		//测试
		Node pNode=head;
		while(pNode!=null) {
			System.out.println(pNode.val);
			pNode=pNode.next;
		}
	}
	
	public static void rmRepeat(Node head) {
		if(head==null) {
			return;
		}
		HashSet<Integer> hashset=new HashSet();
		hashset.add(head.val);
		
		Node pre=head;
		Node cur=pre.next;
		while(cur!=null) {
			if(hashset.contains(cur.val)) {
				pre.next=cur.next;
			}
			else {
				hashset.add(cur.val);
				pre=cur;
			}
			cur=cur.next;
		}
	}
}

posted on   coding_gaga  阅读(143)  评论(0编辑  收藏  举报

编辑推荐:
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示