题目:
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.
题解:
俩指针走的经典题,无需多说。但是需要注意处理当n大于或等于实际实际链表长度的情况。
/**
* 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* ahead = head;
ListNode* behind = head;
if(!head || n <= 0)
return head;
else if(!head->next && n == 1)
{
return NULL;
}
int step = 0;
while(step < n && ahead)
{
step++;
ahead = ahead->next;
}
if(!ahead && step == n)
{
head = head->next;
delete behind;
return head;
}
else if(!ahead && step < n)
return head;
while(ahead->next)
{
ahead = ahead->next;
behind = behind->next;
}
ListNode* temp = behind->next;
behind->next = temp->next;
delete temp;
return head;
}
};