Nth to Last Node in List

题目描述

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.

链接地址

解法ListNode *nthToLast(ListNode *head, int n) {// write your code hereif (head == NULL || n < 0) {// input is errorreturn 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 errorreturn NULL;}while (second != NULL) {first = first->next;second = second->next;}return first;}

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

,力微休负重,言轻莫劝人。

Nth to Last Node in List

相关文章:

你感兴趣的文章:

标签云: