My 2 pointer Java accepted solution


  • 0
    T
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode p1 = head, p2 = head;
            for(int i = 0; i < n; i++) {
                p2 = p2.next;
                if(p2 == null)
                    return head.next;
            }
                
            while(p2.next != null){
                p2 = p2.next;
                p1 = p1.next;
            }
            
            p1.next = p1.next.next;
            
            return head;
        }
    }

  • 0
    Y

    Hello, thanks for your solution. Could you explain how you got the idea?
    Here's my solution, it's not working. Could you help me with that? Thank you!

    if(n==0){
    return head;
    }
    ListNode front = new ArrayList();
    ListNode end = new ArrayList();
    front = head;
    end = head;
    int length = 1;
    while(! front.next.equals(null)){

    	front = front.next;
    	length++;
    }
    int step = length – n+1; // step is how many node from the head
    for(int i=1; i<step-1; ++i){
    	end = end.next;
    }
    	front = end.next.next;
    	end.next = front;
    	return head;
    

  • 0
    T

    basically, I use 2 pointers p1 and p2. p2 is n nodes before p1, and when p2 reaches the last node, p1 is just at n+1th node from end of list. So just need to set p1.next = p1.next.next to remove the nth node.


  • 0
    Y

    Thank you so much for your explain!


Log in to reply
 

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