leetcode 算法题876 (简单229) 链表的中间结点

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/FYuu95100/article/details/102711306

leetcode 算法题876 (简单229) 链表的中间结点

  • 题目介绍
给定一个带有头结点 head 的非空单链表,
返回链表的中间结点。
如果有两个中间结点,
则返回第二个中间结点。
  • 示例

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5]) 返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。 注意,我们返回了一个 ListNode 类型的对象 ans,这样: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.

输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6]) 由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。

  • 提示

给定链表的结点数介于 1 和 100 之间。

  • 解法一
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
  if(!head) {
    return null;
  }
  let slow = head, fast = head.next;
  while(fast) {
    slow = slow.next;
    fast = fast.next && fast.next.next;
  }
  return slow;
};

执行用时 : 48 ms, 在所有 JavaScript 提交中击败了99.68%的用户

内存消耗 : 33.7 MB, 在所有 JavaScript 提交中击败了23.81%的用户

  • 解法二
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
  if(!head) {
    return null;
  }
  let temp = [];
  while(head) {
    temp.push(head);
    head = head.next;
  }
  return temp[Math.floor(temp.length / 2)];
};

执行用时 : 52 ms, 在所有 JavaScript 提交中击败了98.73%的用户

内存消耗 : 33.7 MB, 在所有 JavaScript 提交中击败了23.81%的用户

猜你喜欢

转载自blog.csdn.net/FYuu95100/article/details/102711306