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

19 Remove Nth Node From End of List

2015-08-25 17:15 525 查看
题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

题目:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

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.
Note:
Given n will always be valid.
Try to do this in one pass.


解题思路:

这题是很经典的求链表中倒数第 k 个结点问题。以前在《编程之美》里见过。

这题的思路是,维护两个指针,它们之间相差 k 个结点,当前面那个结点到达链表尾时,后面那个指针正好到达倒数第 k 个结点的前驱结点。

用题目中的例子做个解释。

第一个指针从头结点开始向后移动 n = 2 个结点,移动到 3。此时第二指针正指向头结点,它们之间相差 2 个结点。然后第一个指针和第二个指针同时向后移动,直至第一个指针指向链表最后一个结点。即,当第一个指针指向 5 时,第二个指针指向 3(倒数第二个结点的前驱)。

需要注意的是,当 n 正好等于链表长度时,第一个指针从头结点开始向后移动 n 个结点后指向了链表最后一个结点的后继,也就是 null。这时可以断定,要删除的结点就是链表第一个结点,只要将头结点的后继返回即可。

注意:

要特别注意特殊的情况。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return head;
ListNode tmp = head;
while(n -- > 0)
tmp = tmp.next;
if(tmp == null)
return head.next;
ListNode k = head;
while(tmp.next != null) {
tmp = tmp.next;
k = k.next;
}
k.next = k.next.next;
return head;
}
}


207 / 207 test cases passed.
Status: Accepted
Runtime: 276 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: