Java solution using 2 stacks


  • 0
    S
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            Stack<ListNode> st1 = new Stack<ListNode>();
            Stack<ListNode> st2 = new Stack<ListNode>();
            ListNode tmp = head,tmp1=null,head2=null;
            int len=0;
            while(tmp!=null){
                st1.push(tmp);
                //len++;
                tmp=tmp.next;
            }
            int k=1;
            while(!st1.isEmpty()){
                if(k==n) st1.pop();
                else st2.push(st1.pop());
                k++;
            }
            
            while(!st2.isEmpty()){
                if(tmp1==null) {
                    tmp1=new ListNode(st2.pop().val);
                    head2=tmp1;
                }else{
                    tmp1.next = new ListNode(st2.pop().val);
                    tmp1=tmp1.next;
                }
            }
    
            return head2;
            
        }
    }
    

Log in to reply
 

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