forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnth-to-last-node-in-list.cpp
More file actions
44 lines (37 loc) · 882 Bytes
/
Copy pathnth-to-last-node-in-list.cpp
File metadata and controls
44 lines (37 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Time: O(n), n is lengh of the linked list.
// Space: O(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) {
ListNode *slow = head;
ListNode *fast = head;
// fast is n-step ahead.
while (n > 0) {
fast = fast->next;
--n;
}
// When fast reaches the end, slow must be nth to last node.
while (fast != nullptr) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
};