题目描述
leetcode - 19:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
解题关键
- 链表
碎碎念
中等题因为要求是 一次 循环。所以用两个TreeNode节点tmp和ntmp,ntmp = tmp - n
。简单来说就是tmp往前移动n以后ntmp才开始移动。
代码
/**
* 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* tmp = new ListNode(0);
ListNode* ntmp = new ListNode(0);
tmp->next = head;
ntmp->next = head;
int flag=0;
while(tmp!=NULL){
tmp=tmp->next;
if(flag>n){
ntmp=ntmp->next;
}
flag++;
}
if(ntmp->next==head){
return head=head->next;
}
ntmp->next = ntmp->next->next;
return head;
}
};