【每日编程09】移除重复节点和打印链表

题目1: 移除重复节点

【每日编程09】移除重复节点和打印链表

class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        ListNode pre = null, cur = head;
        HashSet<Integer> set = new HashSet<>();
        while(cur != null){
            if(set.contains(cur.val)){
                pre.next = cur.next;
            }else{
                set.add(cur.val);
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}

题目2: 从尾到头打印链表

【每日编程09】移除重复节点和打印链表

解题思路:
利用栈先进后出的特点

class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<>();
        while(head != null){
            stack.addLast(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for(int i = 0; i < res.length; i++){
            res[i] = stack.removeLast();
        }
        return res;
    }
}
上一篇:CF 1624G - MinOr Tree


下一篇:哈希表、哈希桶数据结构以及刨析HashMap源码中哈希桶的使用