题目描述:
Given a linked list, remove the nth node from the end of list and return its head.
例子:
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.
分析:
题意:给定一个单链表,移除它的倒数第n个结点并返回。
思路:为了方便操作,我们用指针h建立一个空结点(方便指针pre的操作,同时也为了应对“删除第一个结点”这种情况),使其next指针指向指针head。初始化指针pre指向指针h,指针p和q指向指针head,接下来分三步:①指针q向前移动(n-1)步;②指针pre、p、q同时向前移动,直到指针q到达尾结点;③修改指针pre指向结点的next指针指向指针p指向结点的next指针指向的结点,并删除指针p指向的结点,最后返回指针h指向结点的next指针。
代码:
#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// Exceptional Case:
if(!head){
return head;
}
ListNode* h = new ListNode(-1), *pre = h, *p = head, *q = head;
h->next = head;
for(int i = 1; i <= n - 1; i++){
q = q->next;
}
while(q->next){
q = q->next;
pre = pre->next;
p = p->next;
}
pre->next = p->next;
delete(p);
return h->next;
}
};