Share my solution without using two pointers.


  • -1
    A
     public static ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode tempHead = head;
            int count = 0;
            while(head != null)
            {
                count ++;
                head = head.next;
            }
            head = tempHead;
            if (count > n)
            {
    	        for (int i = 0; i < count-n-1; i++)
    	            head = head.next;
            	head.next= head.next.next;
            }
            else
            	return tempHead.next;
            return tempHead;
        }

  • 0
    K

    your code have to traverse the linked list twice.


  • 0
    A

    Ya I know lol. But the other one with two loops got 2 thumbs ups T.T


Log in to reply
 

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