leetcode876. 链表的中间结点

876. 链表的中间结点

方法一:

最简单的做法,先求出整个链表的长度,再求1/2处节点的位置。

/**
 * 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) {
        if(head == nullptr) return nullptr;
        int cnt = 0;
        ListNode *cur = head;
        while(cur!=nullptr){
            ++ cnt;
            cur = cur->next;
        }

        cnt = cnt / 2;
        cout << cnt << endl;
        while(cnt --){
            head = head->next;
        }
        return head;
    }
};

时间很快,空间击败了7%

在C++中,++cnt比cnt++要快一些。

方法二:

经典双指针,快指针比满指针快一倍。但是比较坑的地方在于,在双数的时候,要特别注意边界问题。

/**
 * 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 *f = head;
        ListNode *s = head;

        while(f ->next != nullptr && f->next->next != nullptr){
            f = f->next->next;
            s = s->next;
        }
        
        if(f->next != nullptr){
            s = s->next;
        }
        return s;
    }
}; 
posted @ 2023-03-31 23:22  luxiayuai  阅读(17)  评论(0)    收藏  举报