难度
- 简单
- 中等
-
标签
题目描述
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]输出:[1, 2, 3]
实例2:
输入:[1, 1, 1, 1, 2]输出:[1, 2]
题解
1. 哈希表
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/import java.util.HashSet;class Solution {public ListNode removeDuplicateNodes(ListNode head) {if(head == null) {return null;}ListNode cur = head;HashSet<Integer> set = new HashSet();while(cur != null && cur.next != null) {set.add(cur.val);if(set.contains(cur.next.val)) {cur.next = cur.next.next;} else {cur = cur.next;}}return head;}}
