美文网首页数据结构和算法分析数据结构与算法
Leetcode-面试题 02.01 移除重复节点

Leetcode-面试题 02.01 移除重复节点

作者: itbird01 | 来源:发表于2021-10-04 16:31 被阅读0次

面试题 02.01. 移除重复节点

解题思路

1.遍历链表,保持两个指针,一个pre,一个current,同时用hashset存储已遍历到的值元素
2.遇到已经出现过的值元素,直接进行链表删除当前节点,即将pre.next指向current.next
3.pre指针、current.next需要注意,节点空时,不再遍历

解题遇到的问题

1.这里用到一个之前的小知识点,用hashset存储数据,如果遇到重复的,add会返回false

后续需要总结学习的知识点

链表的基础知识和遍历、操作,需要总结

##解法1
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        ListNode pre = head;
        ListNode current = head;
        HashSet<Integer> existValue = new HashSet<Integer>();

        while (current != null) {
            if (!existValue.add(current.val)) {
                pre.next = current.next;
            } else {
                pre = current;
            }
            current = current.next;
        }
        return head;
    }

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }
}

相关文章

网友评论

    本文标题:Leetcode-面试题 02.01 移除重复节点

    本文链接:https://www.haomeiwen.com/subject/msglnltx.html