LeetCode OJ:Remove Nth Node From End of List(倒序移除List中的元素)
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个元素,开始想用递归做,但是一直失败,没办法看了一下别人的答案,如果总数为N那么倒着第n个相当于正着第N-n个,N的计数通过一次遍历计数即相对的可以得到,代码如下:
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 ListNode * p, * q, * pPre; 13 pPre = NULL; 14 p = q = head; 15 while(--n > 0) 16 q = q->next; 17 while(q->next){ 18 pPre = p; 19 p = p->next; 20 q = q->next; } 21 if(pPre == NULL){ 22 head = p->next; 23 delete p; 24 }else{ 25 pPre->next = p->next; 26 delete p; 27 } 28 return head; 29 } 30 };