题目:(力扣)
思路1:
代码1:
class Solution {
public ListNode middleNode(ListNode head) {
if(head==null){//链表为空,没有中间节点
return null;
}
ListNode cur=head;
int size=0;
while(cur!=null){
size++;
cur=cur.next;
}
cur=head;
int n=size/2;
while(n!=0){
cur=cur.next;
n--;
}
return cur;
}
}
运行结果1:
思路2:
代码2:
idea代码:
public ListNode middleNode1(){
if(head==null){
return head;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){//当链表长度为偶数时的结束条件是fast==null,当链表长度为
//奇数时,结束条件为fast.next==null,两个条件之间要用&&
//不能用||,而且fast!=null在前,要先判断fast是不是等于null
//要是先判断fast.next!=null那么当fast==null时会出现空指针异常
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}
力扣代码:
class Solution {
public ListNode middleNode(ListNode head) {
if(head==null){
return head;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}
运行结果2: