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;
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-528331.html
Optimize
nothing文章來源地址http://www.zghlxwxcb.cn/news/detail-528331.html
到了這里,關(guān)于【每日一題】Leetcode - 19. Remove Nth Node From End of List的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!