码迷,mamicode.com
首页 > 其他好文 > 详细

Nth to Last Node in List

时间:2015-07-06 21:45:46      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:lintcode

题目描述

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

Nth to Last Node in List

标签:lintcode

原文地址:http://blog.csdn.net/richard_rufeng/article/details/46779175

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!