题目
/**
* @Author:linjunbo
* @Description:
* @Date: 2020/3/17 10:13
*/
/**
* 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
* <p>
* 示例1:
* <p>
* 输入:[1, 2, 3, 3, 2, 1]
* 输出:[1, 2, 3]
* 示例2:
* <p>
* 输入:[1, 1, 1, 1, 2]
* 输出:[1, 2]
* 提示:
* <p>
* 链表长度在[0, 20000]范围内。
* 链表元素在[0, 20000]范围内。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
解题
public static ListNode removeDuplicateNodes(ListNode head) {
ListNode thisNode = head;
ListNode beforeNode = null;
Set<Integer> set = new HashSet<>();
while (thisNode != null) {
if (!set.add(thisNode.val)) {
beforeNode.next = thisNode.next;
thisNode.next = null;
thisNode = beforeNode.next;
} else {
beforeNode = thisNode;
thisNode = thisNode.next;
}
}
return head;
}