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; } }
解题思路:
利用栈先进后出的特点
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; } }