题目:链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
示例2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
//不管是奇数个还是偶数个,都是从头向后走 size/2 步
int step = size(head)/2;
ListNode cur = head;
for(int i = 0; i < step; i++) {
cur = cur.next;
}
return cur;
}
//计算链表大小
private int size(ListNode head) {
int size = 0;
for(ListNode cur = head; cur != null; cur = cur.next) {
size++;
}
return size;
}
}