Two pointers Java solution with comments


  • 0
    W
    //思路:先后两根指针。考虑到会删除头指针,新建一个dummy头结点
    public ListNode removeNthFromEnd(ListNode head, int n) {
    	ListNode dummy = new ListNode(0);
    	dummy.next = head;
    	ListNode p1 = dummy; //p1指向的是被删除节点的前一位
    	ListNode p2 = head; //p2初始指向head	
    	while(n > 0) { //p2前进n位
    		p2 = p2.next;  
    		n--;
    	}
    	while(p2 != null) { //p1与p2相差n+1位
    		p1 = p1.next;
    		p2 = p2.next;
    	}
    	p1.next = p1.next.next; //跳过要删除的节点
    	return dummy.next;
    }

Log in to reply
 

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