20220924 - 876. Middle of the Linked List 链表的中间结点(快慢指针)

76 阅读1分钟

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.

Example 1:

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

Example 2:

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:

  • The number of nodes in the list is in the range [1, 100].
  • 1 <= Node.val <= 100

Solution

快慢指针:当快指针走到终点时慢指针所指的就是中间结点

  • 奇数个结点是正好是中间结点
  • 偶数个结点时是第一个中间结点
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* middleNode(struct ListNode* head){
    struct ListNode *fast, *slow;
    fast = head->next;
    slow = head;
    while (fast && fast->next) {
        fast = fast->next->next;
        slow = slow->next;
    }
    if (fast == NULL) return slow;
    else return slow->next;
}

题目链接: 876. 链表的中间结点 - 力扣(LeetCode)