Using a stack - push all elements, then pop n elements. Also using a sentinel node.


  • 0
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode sentinel = new ListNode(0);
            sentinel.next = head;
            
            Stack<ListNode> stack = new Stack<>();
            ListNode ptr = head;
            stack.push(sentinel);
            for(; ptr != null; ptr = ptr.next) {
                stack.push(ptr);
            }
            
            ListNode lastPopped;
            for(int i = 1; i <= n; i++) {
                lastPopped = stack.pop();
            }
            ListNode stackTop = stack.peek();
            stackTop.next = lastPopped.next;
            
            return sentinel.next;
        }
    }
    

Log in to reply
 

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