给你单链表的头结点 head
,请你找出并返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
方法一:数组
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
//方法一:数组
class Solution {
public ListNode middleNode(ListNode head) {
ListNode[] A = new ListNode[100];
int t = 0;
while (head != null) {
A[t++] = head;
head = head.next;
}
return A[t / 2];
}
}
复杂度分析
-
时间复杂度:O(N),其中 N 是给定链表中的结点数目。
-
空间复杂度:O(N),即数组
A
用去的空间。
方法二:单指针法
//方法二:单指针法
class Solution {
public ListNode middleNode(ListNode head) {
int n = 0; //记录遍历完链表后的长度
ListNode cur = head;
while (cur != null) {
++n;
cur = cur.next;
}
int k = 0;
cur = head;
while (k < n / 2) {
++k;
cur = cur.next;
}
return cur;
}
}
复杂度分析
-
时间复杂度:O(N),其中 N 是给定链表的结点数目。
-
空间复杂度:O(1),只需要常数空间存放变量和指针。
方法三:快慢指针法
//方法三:快慢指针法
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;
}
}
复杂度分析
- 时间复杂度:O(N),其中 N 是给定链表的结点数目。
- 空间复杂度:O(1),只需要常数空间存放 slow 和 fast 两个指针。