Java solution using a stack


  • 0
    J
    public ListNode removeNthFromEnd(ListNode head, int n) {
      Deque<ListNode> stack = new ArrayDeque<ListNode>();
    
      ListNode ptr = head;
      while(ptr != null) {
        stack.push(ptr);
        ptr = ptr.next;
      }
    
      // Short circuit for head / tail
      if (stack.size() <= 1) {
        return null;
      } else if (stack.size() == n) {
        return head.next;
      } else if (n == 1) {
        ListNode last = stack.pop();
        ListNode target = stack.pop();
        target.next = null;
        return head;
      }
    
      ListNode currNode = stack.pop();
      ListNode prevNode = stack.pop();
      for (int i=2; i<n; ++i) {
        currNode = prevNode;
        prevNode = stack.pop();
      }
    
      stack.pop().next = currNode;
    
      return head;
    }

Log in to reply
 

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