【LeetCode】Remove Nth Node From End of List

来源:互联网 发布:触摸屏查询网站源码 编辑:程序博客网 时间:2024/06/02 07:09

题目描述:

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;}};


0 0
原创粉丝点击