您的位置:首页 > Web前端 > Node.js

Remove Nth Node From End of List

2015-07-18 10:52 603 查看
题目:

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个节点,删除这个节点,并返回链表头节点head。

思路:

    1.因为链表是单向的,不能从后往前数,为了找到从后往前的第n个节点,可以首先计算出链表的节点数num;
      2.找到节点总数num,可以定位到第n个节点,但是要考虑几种情况:
                                                                                                                           (1)链表为空时,直接返回NULL;

                                                                                                                           (2)当num与n相等时,表示删除头节点;

                                                                                                                           (3)当num与n不相等时,头节点head不用改变,只需找到倒数第n个节点并删除即可。

代码:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息