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.
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.
Note:
- The number of nodes in the given list will be between
1
and100
.
题目:给定一个非空单链表的表头head,返回链表中间的节点。如果有两个中间节点,则返回第二个中间节点。假设1<=输入链表的节点总数<=100。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
实现思路1:比较直观的思路是用一个可遍历元素的数据结构将所有节点保存下来,比如FIFO队列。将所有节点存入队列后可以得到节点总数N,此时如果记head是第1个节点,那么第N/2个节点是就我们需要的结果。
class Solution {
public ListNode middleNode(ListNode head) {
Queue<ListNode> q = new LinkedList<>();
while (head != null) {
q.offer(head);
head = head.next;
}
int size = q.size();
for (int i = 0; i < size / 2; i++)
q.poll();
return q.peek();
}
}
实现思路2:与思路1相似,由于题目假设了输入链表的节点总数不会超过100个,因此可使用一个容量为100的数组保存这些节点,然后index=N/2的节点就是最终结果。
class Solution {
public ListNode middleNode(ListNode head) {
ListNode[] array = new ListNode[100];
int count = 0;
while (head != null) {
array[count++] = head;
head = head.next;
}
return array[count / 2];
}
}
实现思路3:使用快慢指针,其中快指针fast每次向下移动两个节点,慢指针slow每次向下移动一个节点。假设总节点数为N,那么当fast指向最后一个节点时,fast指针扫过的节点总数为N。由于slow指针的速度恰好是fast的一半,那么slow指针恰好扫过N/2个节点,此时slow指向的节点就是最终结果。
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
参考资料: