给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
提示:
- 给定链表的结点数介于 1 和 100 之间。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
//遍历一遍记录长度
int count = 0;
ListNode temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
//移到中间位置
count /= 2;
temp = head;
while (count > 0) {
count--;
temp = temp.next;
}
return temp;
}
}