Simple Java solution using Stack


  • 0
    B
    public int[] twoSum(int[] nums, int target) {
                Stack<ListNode> nodeStack = new Stack<>();
                ListNode current  = head;
                while (current != null) {
                    nodeStack.push(current);
                    current = current.next;
                }
                for (int i = 0; i < n; i++) {
                    nodeStack.pop();
                }
    
                if (nodeStack.empty()) {
                    return head.next;
                }
                ListNode previousRemoved = nodeStack.peek();
                ListNode currentRemoved = previousRemoved.next;
                ListNode nextRemoved = currentRemoved.next;
                previousRemoved.next = nextRemoved;
    
                return head;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.