-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path[lint]. Nth to Last Node in List.java
More file actions
executable file
·65 lines (54 loc) · 1.37 KB
/
[lint]. Nth to Last Node in List.java
File metadata and controls
executable file
·65 lines (54 loc) · 1.37 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
E
tags: Linked List, Lint
#### Linked List
- 先找到nth node
- 然后head开始跑
- node 到底,而head ~ node刚好是 n 距离。所以head就是要找的last nth
```
/*
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 Expand
Cracking The Coding Interview Linked List
Thinking process:
1. Find nth node in normal order.
2. Have a head at index0.
3. Move both head and nth node. WHen nth node hit null/end, then the moving head is the nth to last node in list.
*/
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @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 || n < 0) {
return null;
}
int count = 0;
ListNode node = head;
while (node != null && count < n) {
node = node.next;
count++;
}
while (node != null) {
node = node.next;
head = head.next;
}
return head;
}
}
```