Nth to Last Node in List

Description

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.

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode *nthToLast(ListNode *head, int n) {
        // write your code here
        if (!head) {
            return nullptr;
        }
        int diff = n;
        ListNode* cur = head;
        ListNode* last = head;
        // find new pos of cur, with 1 step advanced from last
        while (cur && diff > 1) {
            cur = cur->next;
            --diff;
        }
        // when cur->next reach nullptr, last is the last N node
        while (cur->next) {
            cur = cur->next;
            last = last->next;
        }
        return last;   
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""