Skip to content

Commit b8caf8a

Browse files
authored
Create 0876-middle-of-the-linked-list.kt
1 parent bcdf4ad commit b8caf8a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Example:
3+
* var li = ListNode(5)
4+
* var v = li.`val`
5+
* Definition for singly-linked list.
6+
* class ListNode(var `val`: Int) {
7+
* var next: ListNode? = null
8+
* }
9+
*/
10+
class Solution {
11+
// use two pointers, fast one that is 2x fast as slow, which will reach end when slow reaches mid
12+
fun middleNode(head: ListNode?): ListNode? {
13+
if(head == null) return null
14+
var slow = head; var fast = head
15+
while(fast != null && fast?.next != null){
16+
slow = slow?.next
17+
fast = fast?.next?.next
18+
}
19+
return slow
20+
}
21+
}

0 commit comments

Comments
 (0)