Leetcode之 链表的中间结点

题目描述

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

思路

  1. 利用栈,先压入统计链表大小,之后弹出至中间位
  2. 利用数组,先统计大小,然后返回中间位
  3. 快慢指针法,用两个指针 slow 与 fast 一起遍历链表。slow 一次走一步,fast 一次走两步。那么当 fast 到达链表的末尾时,slow 必然位于中间。

代码

方法一:

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        int count = 0;
        if(head==NULL)
            return NULL;
        stack<ListNode*> s;
        ListNode* cur = head;
        while(cur!=NULL)
        {
            s.push(cur);
            count++;
            cur = cur->next;
        }
        int nb = count;
        while(nb>count/2+1)
        {
            s.pop();
            nb--;
        }
        return s.top();
    }
};

方法二:

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        int count = 0;
        if(head==NULL)
            return NULL;
        vector<ListNode*> s;
        ListNode* cur = head;
        while(cur!=NULL)
        {
            s.push_back(cur);
            count++;
            cur = cur->next;
        }
        return s[count/2];
    }
};

方法三:

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        if(head==NULL)
            return NULL;
        ListNode* fast = head;
        ListNode* slow = head;
        int a = 0;
        while(fast!=NULL)
        {
            fast = fast->next;
            if(a == 1)
            {
                slow= slow->next;
                a = 0;
            }
            else
                a = 1;
        }
        return slow;
    }
};
发布了85 篇原创文章 · 获赞 0 · 访问量 376

猜你喜欢

转载自blog.csdn.net/weixin_38312163/article/details/105040038