Remove Nth Node From End of List
Total
Accepted: 86119 Total
Submissions: 307466 Difficulty: Easy
Given a linked list, remove the nth node from the end of list and return its head.
For example,
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.
Note:
Given n will always be valid.
Try to do this in one pass.
思路:
1).考虑一下被删除节点是head的情况。
2).控制两个指针p,q,相差为n,当q指向链末尾,则p下一个节点为要删除的节点。
/**
* 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(n<=0){
return head;
}
ListNode* tail=head;
while(n--){
tail=tail->next;
}
ListNode* p=head;
if(tail==NULL){
head=head->next;
//delete p;
return head;
}
while(tail->next!=NULL){
tail=tail->next;
p=p->next;
}
//tail=p->next;
//delete tail;
p->next=p->next->next;
return head;
}
};