19.Remove Nth Node From End of List [难度:中等]
【题目】
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
【解题C++】
(题外话:刚还想说用不惯LeetCode,感觉只给个函数接口不方便调试而且提交好慢好慢,然后就发现原来这是可以自己编辑输入样例的!而且也有调试窗口,不过我不会用......果然还是我太菜了= = 说来不好意思我至今都不会调试,永远只会用printf输出中间值找bug)
这道题如果按照常规思路,那就是先遍历一遍链表,求出长度len,再遍历第二遍删除第len-n个结点。但是题目可说了,“Could you do this in one pass?” 要想只遍历一遍就能删除倒数第n个结点,这时候就得靠我们万能的指针(广义上的指针)了!先让指针i走n步,再让指针i和j同时走,这样一来,等i遍历完毕时,j比i还慢了n步,而此时j所处的位置正是倒数第n个数!
这样做也不会增加空间复杂度~虽然最后的代码有两个while循环,但其实加起来的次数相当于一次啦^ ^
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *i,*j;
i = j = head;
//i先行n步
while(n--)
i = i->next;
//一定别忘了特殊判断走到尾的情况,不然i为空再进入下面的while循环会出问题的!!!
if(!i) return j->next;
//i和j同时走
//循环体是i->next不是i,因为要删除该结点,必须得有前结点在场才行~
while(i->next)
{
i = i->next;
j = j->next;
}
//此时的j是要删除结点的前结点
j->next = j->next->next;
return head;
}
};
【解题Python】
思路同C++。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
i = j = head
for x in range(n):
i = i.next
if i is None:
return j.next
while i.next:
i = i.next
j = j.next
j.next = j.next.next
return head