leetCode-0876_链表的中间结点

题目描述

英文题目

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:

1
2
3
4
5
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.

Example 2:

1
2
3
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.

Note:

  • The number of nodes in the given list will be between 1 and 100.
中文题目

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

示例 1:

1
2
3
4
5
输入:[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.

示例 2:

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

提示:

  • 给定链表的结点数介于 1100 之间。

解决方法

方法一
  • 描述
  • 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
链表的中间结点

@param head 不带头结点
@return 链表中间结点之后的链表
*/
struct ListNode *middleNode(struct ListNode *head)
{
struct ListNode *slow = head;
struct ListNode *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}

return slow;
}

/**
链表的中间结点测试
*/
void middleNode_test()
{
SingleLinkListNode *head = single_link_list_create();
single_link_list_insert_tail(head, 1);
single_link_list_insert_tail(head, 2);
single_link_list_insert_tail(head, 3);
single_link_list_insert_tail(head, 4);
single_link_list_insert_tail(head, 5);
// single_link_list_insert_tail(head, 6);

printf("========链表的中间结点========\n");
single_link_list_dump_head(head);
SingleLinkListNode *new = middleNode(head->next);
single_link_list_dump(new);
}

题目来源

Middle of the Linked List

链表的中间结点

线性表相关代码

数据结构-线性表