本文共 788 字,大约阅读时间需要 2 分钟。
为了解决这个问题,我们需要找到给定单链表的中间结点。如果链表的长度为奇数,返回中间的那个结点;如果长度为偶数,返回第二个中间结点。
(length + 1) / 2 个节点;如果是偶数,中间结点是第 length / 2 个节点。class Solution {public: ListNode* middleNode(ListNode* head) { int num = 0; ListNode* current = head; while (current != nullptr) { num++; current = current->next; } int k = num / 2; current = head; for (int i = 0; i < k; i++) { current = current->next; } return current; }}; while 循环遍历链表,计算节点的总数 num。num / 2 计算出要移动的步数 k。k 步移动,返回中间节点。这种方法通过两次遍历链表,第一次计算长度,第二次移动到中间节点,时间复杂度为 O(n),其中 n 是链表的长度。
转载地址:http://rhhv.baihongyu.com/