【每日一题】Leetcode - 19. Remove Nth Node From End of List

Question

Train of thought

Drawing on the method of finding midpoints in linked lists, use quick slow pointer

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
          
   

    public ListNode removeNthFromEnd(ListNode head, int n) {
          
   
        ListNode pioneer = head, offspring = head, bHead = head;
        while (n-- > 0 && head != null) {
          
   
            pioneer = head.next;
            head = head.next;
        }

        if (pioneer == null) {
          
   
            return bHead.next;
        }
 
        while (pioneer.next != null) {
          
   
            offspring = offspring.next;
            pioneer = pioneer.next;
        }

        offspring.next = offspring.next.next;

        return bHead;
    }

}

Optimize

nothing

经验分享 程序员 微信小程序 职场和发展