876. 链表的中间结点
题解
快慢指针
使用两个指针 slow 和 fast 一起遍历,slow 一次走一步,fast 一次走两步,当 fast 走到结尾时 slow 则在中间,返回 slow
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户 内存消耗:35.8 MB, 在所有 Java 提交中击败了24.33% 的用户
class Solution {public ListNode middleNode(ListNode head) {ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}return slow;}}
使用辅助数组
链表的缺点是不能使用索引访问元素,使用额外的数组空间存储链表节点,假设链表一共有 N 个节点,则返回数组中索引为 N/2 的元素
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户 内存消耗:35.8 MB, 在所有 Java 提交中击败了32.47% 的用户
class Solution {public ListNode middleNode(ListNode head) {ArrayList<ListNode> list = new ArrayList<>();while (head != null) {list.add(head);head = head.next;}return list.get(list.size() / 2);}}
遍历两次链表
第一次遍历记录节点数量 N ,第二次遍历到第 N/2 个元素,将该元素返回
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户 内存消耗:35.8 MB, 在所有 Java 提交中击败了43.72% 的用户
class Solution {public ListNode middleNode(ListNode head) {int n = 0;ListNode cur = head;while (cur != null) {cur = cur.next;n ++;}cur = head;for (int i = 0; i < n / 2; i++) {cur = cur.next;}return cur;}}
