题目描述:
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.
第二种是递归,从后往前计算长度,也差不多吧……需要注意下移出第一节点时的处理。
因为if后面的==写成了=,没有one pass,真是想哭……
class Solution {
public:
ListNode *next;
ListNode *removeNthFromEnd(ListNode *head, int n) {
next = NULL;
if (recusive(head, n) == n)
return head->next;
return head;
}
int recusive(ListNode *node, int n){
int num = 1;
if (node->next)
num += recusive(node->next, n);
if (num == n - 1)
next = node;
if (num == n + 1)
node->next = next;
return num;
}
};