首页 > 其他 > 详细

LeetCode 876. Middle of the Linked List(获得链表中心结点)

时间:2020-02-28 13:28:49      阅读:66      评论:0      收藏:0      [点我收藏+]

题意:获得链表中心结点。当有两个中心结点时,返回第二个。

分析:快慢指针。

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

  

LeetCode 876. Middle of the Linked List(获得链表中心结点)

原文:https://www.cnblogs.com/tyty-Somnuspoppy/p/12376649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!