标签:
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 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeNthFromEnd(ListNode* head, int n) { 12 int l=2; 13 int i=2; 14 ListNode *temp,*tt; 15 temp=head->next; 16 if(temp==NULL) 17 { 18 if(n==0) return head; 19 else return NULL; 20 } 21 while(temp->next!=NULL) 22 { 23 temp=temp->next; 24 l++; 25 } 26 if(n==l) 27 { 28 return head->next; 29 free(head); 30 } 31 temp=head; 32 while(temp->next!=NULL) 33 { 34 35 if(i==l-n+1) 36 { 37 tt=temp->next; 38 temp->next=tt->next; 39 free(tt); 40 i++; 41 continue; 42 } 43 temp=temp->next; 44 i++; 45 } 46 return head; 47 } 48 };
Remove Nth Node From End of List
标签:
原文地址:http://www.cnblogs.com/hexhxy/p/4797935.html