Concise Java Always Use a FakeHead when Handling Such Problems


  • 1
    M

    The use of fake head makes things very simple. However, the following code will occur a NullPointerException when n =0 and it's kind of memory leak.

    	public ListNode removeNthFromEnd(ListNode head, int n) {
    
    	ListNode fast = head;
    	while (n-- > 0)
    		fast = fast.next;
    
    	ListNode fakeHead = new ListNode(-1);
    	fakeHead.next = head;
    	head = fakeHead;
    
    	while (fast != null) {
    		fast = fast.next;
    		head = head.next;
    	}
    	head.next = head.next.next;
    
    	return fakeHead.next;
    
    }

Log in to reply
 

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