文章目录
- 题目介绍
- 题解
题目介绍
题解
法一:
class Solution {
public ListNode middleNode(ListNode head) {
ListNode cur = head;
int n = 0;
while (cur != null) {
n++;
cur = cur.next;
}
ListNode curr = head;
for (int i = 0; i < n / 2; i++) {
curr = curr.next;
}
return curr;
}
}
法二:快慢指针
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(true){
if(fast == null || fast.next == null){
break;
}
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}