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

花明

关注

阅读 17

2022-01-26

题目1: 移除重复节点

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: 从尾到头打印链表

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

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;
    }
}

精彩评论(0)

0 0 举报