Concise Java Always Use a FakeHead when Handling Such Problems

  • 1

    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 =;
    	ListNode fakeHead = new ListNode(-1); = head;
    	head = fakeHead;
    	while (fast != null) {
    		fast =;
    		head =;
    	} =;

Log in to reply

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