Java, First Post on Group,1ms solution


  • 2

    You take 2 Pointers.
    First you send the first pointer ahead to n positions.
    Then you start incrementing till the the first reach the last node.
    Now you just have to delete the 2nd pointer's node. As it is n positions behind the first pointer.

    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null) {
                return head;
            } else if(head.next == null && n ==1 ){
                return null;
            }
            ListNode current = head;
            for (int i = 0; i < n-1; i++) {
                if (current == null) {
                    return head;
                }
                current = current.next;
            }
            ListNode toDelete = head;
            ListNode beforeToDelete = null;
            while (current.next != null) {
                beforeToDelete = toDelete;
                current = current.next;
                toDelete = toDelete.next;
            }
            if (toDelete.next == null) {
                beforeToDelete.next = toDelete.next;
                return head;
            }
            toDelete.val = toDelete.next.val;
            toDelete.next = toDelete.next.next;
            return head;
        }
    }
    

  • 0
    S

    nice solution!


  • 1
    K

    A shorter one.

     public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode runner = head;
            for(int i = 0; i < n; i++) {
                runner = runner.next;
            }
            if(runner == null) {
                return head.next;
            }
            ListNode secRunner = head;
            while(runner.next != null) {
                secRunner = secRunner.next;
                runner = runner.next;
            }
            secRunner.next = secRunner.next.next;
            return head;
        }
    

  • 0
    J

    Good solution.
    But this is still virtually two passes. You just take these two passes in one loop. With one pointer and two loops I can do the exact same thing.


Log in to reply
 

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