跳至主要內容

Leetcode 876. 链表的中间结点

张威小于 1 分钟数据结构与算法双指针链表

Leetcode 876. 链表的中间结点open in new window

**题目描述:**给你单链表的头结点 head ,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* dummyHead = new ListNode(-1, head);
        ListNode* fast = dummyHead;
        ListNode* slow = dummyHead;
        
        while(fast&& fast->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        if(fast && fast->next == nullptr) {
            slow = slow->next;
        }
        return slow;
    }
};

实际上不需要虚拟头结点即可

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* fast = head;
        ListNode* slow = head;
        
        while(fast&& fast->next) {//如果有两个中间结点,则返回第二个中间结点。
            fast = fast->next->next;
            slow = slow->next;
        }
        
        return slow;
    }
};