下面我用两种方式来演示
第一种:就是先求出链表长度,长度=count,长度除2的值,再从头指针处走num-1次就是返回节点这也是我们常用方法,代码演示:
class Solution {
public ListNode middleNode(ListNode head) {
if(head==null)return null;
if(head.next==null)return head;
ListNode walk=head;
int count=0;
while(walk!=null) {
walk = walk.next;
count++;//每走一步++
}
ListNode headcopy=head;//为保证head节点不变
for (int i = 0; i <count/2 ; i++) {
headcopy=headcopy.next;
}
return headcopy;
}
}
第二种方法:我们先定义连个指针fast和slow,先让他们指向头节点,然后让fast每次走两步,slow每次走一步,fast==null或者fast.next==null结束,画图解释:
链表长度为奇数时:
fast每次走两步,slow每次走一步:
fast每次走两步,slow每次走一步:
链表长度为偶数时结束状态:
代码实现:
class Solution {
public ListNode middleNode(ListNode head) {
if(head==null)return null;
if(head.next==null)return head;
ListNode walk=head;
int count=0;
while(walk!=null) {
walk = walk.next;
count++;//每走一步++
}
ListNode headcopy=head;//为保证head节点不变
for (int i = 0; i <count/2 ; i++) {
headcopy=headcopy.next;
}
return headcopy;
}
}