Nth to Last Node in List

原创 2015年07月06日 21:13:17

题目描述

Find the nth to last element of a singly linked list.

The minimum number of nodes in list is n.
Example

Given a List 3->2->1->5->null and n = 2, return node whose value is 1.

链接地址

http://www.lintcode.com/en/problem/nth-to-last-node-in-list/

解法

     ListNode *nthToLast(ListNode *head, int n) {
        // write your code here
        if (head == NULL || n < 0) {
            // input is error
            return head;
        }
        ListNode *first = head;
        ListNode *second = head;
        int i;
        for ( i = 0; i < n && second != NULL; i++) {
            second = second->next;
        } 
        if (second == NULL && i < n) {
            // Input is error
            return NULL;
        }
        while (second != NULL) {
            first = first->next;
            second = second->next;
        }
        return first;
    }

相关文章推荐

【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】

【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a l...

《leetCode》:Remove Nth Node From End of List

题目描述Given a linked list, remove the nth node from the end of list and return its head.For example, ...

[C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)

Problem: Given a linked list, remove the nth node from the end of list and return its head. For exam...

Leetcode_19_Remove Nth Node From End of List

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41778305 Given a linked list, ...

LeetCode Remove Nth Node From End of List 删除倒数第n个元素

这里的Note的意思应该就是可以不做特殊处理n值了。不过其实特殊处理也就一句语句。 思路: 快指针和慢指针的概念,先一个指针先走,到了离起点n个节点远的时候,慢指针走,等到快指针走到结尾,那么慢指...

[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)

[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)
  • hcbbt
  • hcbbt
  • 2015年03月04日 19:26
  • 2137

【Leetcode】19. Remove Nth Node From End of List

方法一: 思路: (1)若链表为空,直接返回null。 (2)求链表的长度len。 (3)若n==len,则删除的是第一个节点,直接删除后返回即可。 (4)从头开始遍历链表,找到待删除节点cur,并用...

LeetCode OJ 之 Remove Nth Node From End of List ( 删除链表的从尾部数第n个结点 )

题目: Given a linked list, remove the nth node from the end of list and return its head. 删除链表的从尾部数第...

leetcode:单链表之Remove Nth Node From End of List

leetcode:单链表之Remove Nth Node From End of List 题目: Given a linked list, remove the nth node from the ...

leetcode-Remove Nth Node From End of List

此题本来是十分简单的题目,可是由于自己对于指针以及函数参数的理解不是很透彻导致出现很多次问题,主要问题在于对函数传入指针参数,其实传入的是某指针的副本,通过指针的解引用可以修改指针指向的对象的内容,但...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Nth to Last Node in List
举报原因:
原因补充:

(最多只允许输入30个字)