Question
Leetcode - 19. Remove Nth Node From End of List
Train of thought
Drawing on the method of finding midpoints in linked lists, use quick slow pointer
Finding midpoints in linked lists
/**
* 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;
}
}
文章来源:https://www.toymoban.com/news/detail-528331.html
Optimize
nothing文章来源地址https://www.toymoban.com/news/detail-528331.html
到了这里,关于【每日一题】Leetcode - 19. Remove Nth Node From End of List的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!