[JavaScript 刷题] 链表 - 链表的中间结点, leetcode 876

[JavaScript 刷题] 链表 - 链表的中间结点, leetcode 876

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:876. Middle of the Linked List

题目

如下:

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

解题思路

这个题也是比较经典的 easy 题了,主流的解法也是有两种。

大 O 上来说,两种解法都是 O ( n ) O(n) O(n),但是快慢指针毕竟比 double pass 少跑一个便利,实际应用上会快一些。

double pass

直接遍历链表两次,第一次获得链表的长度,第二次获取中间结点。

双指针

这里使用的方法为双指针中的快慢指针,已知需要找的元素是链表中中间的元素,那么就可以让慢指针一次移动 1 下,快指针一次移动两下。这样当快指针跑到了链表的末尾,慢指针正好指向中间。

使用 JavaScript 解题

这里只放快慢指针的解法了。

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */

var middleNode = function (head) {
    
    
  let firstNode = head,
    secondNode = head.next;

  while (secondNode) {
    
    
    firstNode = firstNode.next;
    secondNode = secondNode.next?.next;
  }

  return firstNode;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125211679