leetcode--Remove Nth Node From End of List
1.题目分析
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.
2.解法分析
对于链表的题,双指针法经常用到,这个题目就可以设置两个指针,题意说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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=0)return head;if(head==NULL)return NULL;ListNode *forward=head;int margin=0;
while(margin<n&&forward!=NULL)
{margin++;forward=forward->next;}if(margin<n)return head;ListNode *afterward=head;ListNode *prev=head;while(forward!=NULL)
{prev=afterward;afterward=afterward->next;forward=forward->next;}if(afterward==head)
{prev=head;afterward=head->next;free(head);return afterward;
}prev->next=afterward->next;free(afterward);return head;
}};