您的位置:首页 > Web前端 > Node.js

leetcode题解(十):19. Remove Nth Node From End of List

2019-04-01 13:39 501 查看

题意:移除链表的倒数第n个节点
例子:
Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

public ListNode removeNthFromEnd(ListNode head, int n) {
//依然是两根指针的思路
ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head;

//快指针先走n步
for(int i=1; i<=n+1; i++)   {
fast = fast.next;
}
//快慢指针一起走
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
//慢指针所指的位置就是倒数第n个节点,删除即可
slow.next = slow.next.next;
return start.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: