Java solution 1ms 容易理解


  • 19
    M
    //还是走的快的点(fastNode)与走得慢的点(slowNode)路程差的问题
    	public static ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode headNode = new ListNode(9527);
            headNode.next = head;
            ListNode fastNode = headNode;
            ListNode slowNode = headNode;
            while(fastNode.next != null){
            	if(n <= 0)
            		slowNode = slowNode.next;
            	fastNode = fastNode.next;
            	n--;
            }
            if(slowNode.next != null)
            	slowNode.next = slowNode.next.next;
            return headNode.next;
        }

  • 0
    R

    good one, but why should we consider when n < 0? what does that even mean?


  • 0
    B

    it's only after n<=0 the slow pointer starts iterating over the list for (n-l) times. When it exits the loop it would be pointing to the target node.


  • 0
    Y

    @River3 Because when n > 0, you should only move fast node. Once n <= 0, the fast node is in the right position and you can move both fast and slow node at the same time.


  • 0
    R

    Thank you guys, I misunderstood before, now I get it.

    IMHO, it should be tweak a bit for better coding style:

    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode headNode = new ListNode(9527);
            headNode.next = head;
            ListNode fastNode = headNode;
            ListNode slowNode = headNode;
            while(fastNode.next != null){
            	if(n <= 0){
            	    slowNode = slowNode.next;
            	} else {
            	    n--;
            	}
            	fastNode = fastNode.next;
            }
            if(slowNode.next != null)
            	slowNode.next = slowNode.next.next;
            return headNode.next;
        }
    }

  • 1
    M

    @River3
    thank you very much,now I spend most of my time looking for a job, so I sometimes neglect.


  • 0
    C

    Why you use headNode.next = head? I try use headNode = head, it can pass some testcases, but others can not. I don't know why use headNode.next..


  • 0
    C

    @River3 Why you use headNode.next = head? I try use headNode = head, it can pass some testcases, but others can not. I don't know why use headNode.next..


  • 0
    Y

    @changyan Its because the dummy node has been taken initially. And the input head is assigned to the next pointer of the dummy node. And in the return also function returns the actual head reference. Hope that makes sense.


  • 0
    J

    @River3
    I don't think this chunk of code is in better coding style than the original one. The else statement is unnecessary and the format is more messy

    if(n <= 0){
        slowNode = slowNode.next;
    } else {
        n--;
    }
    

  • 0
    H

    9527 9527 9527!


  • 0
    A

    哈哈哈哈哈哈哈哈哈哈哈,赞👍


Log in to reply
 

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