0%

链表的中间结点-LeetCode

链表的中间结点

链表的中间结点

1
2
3
4
5
6
7
8
9
10
11
12
876.链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
<p>
如果有两个中间结点,则返回第二个中间结点。
<p>
示例 1:
<p>
输入:[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.

Implementation:

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
public class MiddleNode {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
System.out.println(middleNode(head).val);
}

public static 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;
}
}


//Definition for singly-linked list.
class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}