Day6: [LeetCode中等] 19. 删除链表的倒数第N个节点
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
思路:
考察链表基本功而已。
代码:
dirty code凑合看吧
/**
* 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=NULL,*k=head,*p=head;
for(int i=0;i<n-1;i++){
k=k->next;
}
while(1){
if(k->next==NULL){
if(pre==NULL){
return head->next;
}
pre->next=p->next;
p=p->next;
break;
}
k=k->next;
pre=p;
p=p->next;
}
return head;
}
};