Home [Easy] Middle of the Linked List
Post
Cancel

[Easy] Middle of the Linked List

‘Middle of the Linked List’ in LeetCode (Easy)


📌 Problem

https://leetcode.com/problems/middle-of-the-linked-list/

📌 Answer

When traversing the list with a pointer slow, make another pointer fast that traverses twice as fast. When fast reaches the end of the list, slow must be in the middle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Remove Duplicates from Sorted List

[Easy] Convert Binary Number in a Linked List to Integer

Comments powered by Disqus.