1.题目
2.解题思路
先遍历一遍链表,获取链表长度,获取到链表的中间节点
3.代码实现
class Solution {
public ListNode middleNode(ListNode head) {
ListNode temp = head;
int count = 0;
while(temp != null) {
temp = temp.next;
count++;
}
count /= 2;
temp = head;
for (int i = 0; i < count; i++) {
temp = temp.next;
}
return temp;
}
}
4.另一种解题思路
使用快慢指针,快指针每次走两格,慢指针每次走一格
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
作者:LeetCode
链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。