LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

tags: leetcode easy Linked List Two Pointers

876. Middle of the Linked List

Description

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Examples

Example 1:

Odd nodes
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Even nodes
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* middleNode(struct ListNode* head){
    struct ListNode *fast, *slow;
    for(fast = head, slow = head;;){
        // Wether we can jump to the next node
        if(fast->next != NULL){
            // Whether we can jump two nodes?If we can, jump and set slow pointer
            if((fast->next)->next != NULL){
                fast = (fast->next)->next;
                slow = slow->next;
            }
            // If we can only jump ome node, it means the link-list has even nodes and slow is the first middle
            else
                return slow->next;
        }
        // If we can not jump to the next node, it means we have odd nodes and slow is the middle
        else
            return slow;
    }
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* middleNode(struct ListNode* head){
    int count;
    struct ListNode *tmp;
    for(count = 0, tmp = head ; tmp ; count++)
        tmp = tmp->next;
    count /= 2;
    for(int i = 0 ; i < count ; i++)
        head = head->next;
    return head;
}

Complexity

Space Time
$O(1)$ $O(N)$

Result