题目描述:
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 int removeListNode(ListNode* cur, int n){ 12 if(!cur) 13 //链表末尾返回数值 14 return -1; 15 int num = removeListNode(cur->next, n)+1; 16 //当前节点的计数,最后一个节点是0 17 if(num == n) 18 cur->next = cur->next->next; 19 return num; 20 } 21 ListNode* removeNthFromEnd(ListNode* head, int n) { 22 ListNode* pre = new ListNode(0); 23 pre->next = head; 24 int sum = removeListNode(pre, n);//新建一个节点,next为head,防止删除节点在第一个的情况 25 return pre->next; 26 } 27 };