Leetcode19. Remove Nth Node From End of List
原题地址
题目描述
Given a linked list, remove the nth node from the end of list and return its head.
思路
要删除倒数第n个节点,要先找到该节点的前一个节点。可以先遍历链表得出链表中节点个数count,则要删除的节点的前一个节点位于顺数第count-n-1位置处,然后后面进行简单的删除操作即可。
代码实现
/**
* 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) {
if (head==NULL || n<=0){
return NULL;
}
int count=0;
ListNode *p1;
p1=head;
while(p1){
count++;
p1=p1->next;
}
ListNode *p2;
p2=head;
if(count==n){
head=p2->next;
return head;
}
int move=count-n-1;
while(move){
p2=p2->next;
move--;
}
p2->next=p2->next->next;
return head;
}
};