Given a linked list, remove the n-th node from the end of list and return its head.
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.
思考:一道非常基础的题目。找到要删除的节点的前一个节点,以上题为例,欲删除节点为4,那么找到节点3。怎么找到节点3呢?用两个指针相隔n+1,然后一起往前走,直到最后。代码实现如下。
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 if(head==NULL) return NULL; 13 14 ListNode *p = head; 15 ListNode *pre = NULL; 16 int count = 0; 17 while(p) { 18 count++; 19 p = p->next; 20 if(count==n+1) { 21 pre = head; 22 }else if(count>n+1) { 23 pre = pre->next; 24 } 25 } 26 27 if(count<n) return NULL; 28 if(count==n) return head->next; 29 //count>n means the link have more than n node. 30 pre->next = pre->next->next; 31 32 return head; 33 } 34 };