876. Middle of the Linked List (

2018-11-18  本文已影响9人  f1a94e9a1ea7

Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
给一个有头结点的非空单链表,返回中间结点。
如果有两个中间结点,返回第二个。

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

输入:[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.

Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

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

解析:

参考于桐哥优秀

第一种方法:先遍历整个单链表,得到长度,再重新遍历到中间位置。
但是这样就需要循环两次,时间复杂度为 2O(n)

第二种方法:只遍历一遍,使用两个指针 tail 和 mid,tail 指向尾部,tail 每走两步,mid 走一步;结束之后,若 tail 最后走的是一步,说明 tail 走了 (2n +1) 步,总共是偶数个节点,此时 mid 还要走一步

(The following English translation may not be right)

analyze:

refer:桐哥优秀

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
  var tail = mid = head;  
  var count = 0;
  while (tail.next !== null) {
    tail = tail.next;
    count ++;
    if (count === 2) {
      mid = mid.next;
      count = 0;
    }
  }
  if (count === 1) {
    mid = mid.next;
  }
  return mid;

};
上一篇 下一篇

猜你喜欢

热点阅读