Simple Java Solution in one pass. May be helpful.


  • 0
    N
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head==null)return head;
            ListNode early = head;
            while(n>0){
                early = early.next;
                n--;
            }
            if(early==null)return head.next;
            ListNode pres = head;
            ListNode prev=null;
            while(early!=null){
                prev=pres;
                pres = pres.next;
                early = early.next;
            }
            prev.next = pres.next;
            return head;
        }
    }

Log in to reply
 

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