【链表】删除链表中的重复元素

本文介绍了一种使用LinkedHashMap删除链表中重复节点的方法,并实现了一个Java函数。该方法通过遍历链表并记录每个节点出现的次数,再构建一个仅包含单一实例的新链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5


我的代码:

/**
	 * 删除链表中的重复元素
	 * @param pHead 原链表的头结点
	 * @return 返回删除重复元素之后的新的链表的头结点
	 */
	public ListNode deleteDuplication(ListNode pHead) {
		//LinkedHashMap可以按照输入的顺序进行输出
		LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
		ListNode current = pHead;
		
		//遍历一遍原链表,将元素出现的次数存储在map中
		while (current != null) {
			if (!map.containsKey(current.val)) {
				map.put(current.val, 1);
			} else {
				int times = map.get(current.val);
				times++;
				map.put(current.val, times);
			}
			current = current.next;
		}

		ListNode newHead = null;
		ListNode point = null;
		boolean isHead = true;
		Set<Integer> set = map.keySet();
		Iterator<Integer> it = set.iterator();
		
		//根据map中存的值,只用出现一次的值来构造新的链表
		while (it.hasNext()) {
			int temp = it.next();
			if (map.get(temp) == 1) {
				ListNode currentNode = new ListNode(temp);
				if (isHead) {
					newHead = currentNode;
					point = currentNode;
					isHead = false;
					continue;
				}
				point.next = currentNode;
				point = currentNode;
			}
		}
		return newHead;
	}


通过这道题需要学习到的知识点是LinkedHashMap,这个数据结构可以保证map中存储的顺序和添加进去的顺序是一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值