【List-easy】876. Middle of the Linked List 找到链表的中间元素
1. 题目原址
https://leetcode.com/problems/middle-of-the-linked-list/
2. 题目描述
3. 题目大意
给定一个链表,找到链表中处于中间的元素。
4. 解题思路
使用快慢指针。
快指针每次走两步,慢指针每次走一步,当快指针到达链表的末尾时,慢指针的位置就是链表的中间元素
5. AC代码
class Solution {
public ListNode middleNode(ListNode head) {
ListNode h = head;
if(head == null || head.next == null) return head;
ListNode pre1 = head, pre2 = head;
while(pre2 != null && pre2.next != null) {
pre1 = pre1.next;
pre2 = pre2.next.next;
}
return pre1;
}
}