给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
解题思路:
需要注意的就是
1)[1,2] 1
2) [1,2] 2
3) [1] 1
在1)和3)的情况中,待删除节点为首节点,因此pre节点为NULL,需要根据当前是否仅有一个节点做出判断,是直接返回head->next 还是返回null
而在2 中 待删除节点后面没有后继节点了。
/**
* 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 *pre = find_pre(head,n);
if(pre==NULL){
if(head->next) head = head->next;
else head = NULL;
}else {
pre->next = pre->next->next;
}
return head;
}
inline ListNode* find_pre(ListNode* head, int &n){
ListNode *tmp = head, *pre = NULL;
int count = 1;
while(tmp->next){
if(count==n){
pre = head;
}
if(count>n){
pre=pre->next;
}
tmp = tmp->next;
count++;
}
return pre;
}
};