-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMiddleOfTheLinkedList.java
More file actions
47 lines (40 loc) · 1 KB
/
Copy pathMiddleOfTheLinkedList.java
File metadata and controls
47 lines (40 loc) · 1 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
package linkedlist;
// Source : https://leetcode.com/problems/middle-of-the-linked-list/
// Id : 876
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2019-05-29
// Topic : Linked list
// Other :
// Tips :
// Result : 100.00% 100.00%
public class MiddleOfTheLinkedList {
public ListNode middleNode(ListNode head) {
ListNode fast = head, slow = head;
while (fast.next != null) {
fast = fast.next;
if (fast.next == null)
// If there are two middle nodes, return the second middle node.
return slow.next;
else {
fast = fast.next;
slow = slow.next;
}
}
return slow;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/