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

Nth to Last Node in List

2015-07-06 21:13 507 查看
题目描述

链接地址

解法

题目描述

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode