-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathNthToLast.java
More file actions
36 lines (31 loc) · 948 Bytes
/
NthToLast.java
File metadata and controls
36 lines (31 loc) · 948 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
/*NthToLast.java
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.
Tags Cracking The Coding Interview Linked List
*/
public class NthToLast {
/**
* @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 == null || head.next == null || n <= 0) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
for (int i = 0; i < n - 1; i++) {
fast = fast.next;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}