核心思想是:先求出链表长度,然后除以二得到steps,然后从头结点出发,走steps 步,就是中间节点,这个对长度为奇数或者偶数个的链表都适用.
public class Middle {
//给内部类加static,让内部类和List类相关,而和对象不相关
static class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode middleNode(ListNode head) {
int steps=size(head)/2;//求出从头结点开始走的步数
ListNode cur=head;
for(int i=0;i<steps;i++){
cur=cur.next;
}
return cur;
}
public int size(ListNode head) {
//求链表长度
int size = 0;
ListNode cur = head;
while (cur != null) {
cur = cur.next;
size++;
}
return size;
}
}
}