题目描述
给定一个链表,删除链表的倒数第n个节点并返回链表的头指针
例如,
给出的链表为:1->2->3->4->5, n= 2.
删除了链表的倒数第n个节点之后,链表变为1->2->3->5.
备注:
题目保证n一定是有效的
请给出请给出时间复杂度为 O(n) O(n)的算法
示例1
输入
复制
{1,2},2
返回值
复制
{2}
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
ListNode * myHead = new ListNode(0),*slow = myHead, *fast = myHead;
myHead ->next = head;
while(n--) fast = fast ->next;
// 快指针先 走 n 下
while(fast ->next) slow= slow->next, fast = fast ->next;
auto will_del = slow ->next;
slow ->next = slow ->next ->next;
delete will_del;
will_del = myHead;
myHead = myHead ->next;
delete will_del;
return myHead;
}
ListNode * reverse(ListNode* p) {
ListNode* pre = NULL,*next = NULL;
while (p) {
next = p->next,p->next = pre,pre = p ,p=next;
}
return pre;
}
};