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.

分析:

没有什么需要分析,带入个例子检查一下结果对不对就好。

解法:

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) {
        if (head == NULL) {
            return head;
        }
        ListNode* slow = head;
        ListNode* fast = head;
        for (int i = 0; i < n; i++) {
            fast = fast->next;
        }
        while (fast != NULL) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

results matching ""

    No results matching ""