思路:定义两个快慢指针,快指针一次走两步,慢指针一次走一步,当快指针到达尾结点时,慢指针刚好为中间结点,这里需要区分两种情况,当链表中结点数为奇数时,慢指针刚好到达中间结点;当链表中结点数为偶数时候,中间结点有两个,返回一个。
public static ListNote findMidNode(ListNote headNote){
if(headNote==null){
return null;
}
ListNote firstNote = headNote;//快指针
ListNote secondNote=null;
secondNote=headNote;//慢指针
while(firstNote.getNext()!=null){
firstNote=firstNote.getNext();
secondNote=secondNote.getNext();
if(firstNote.getNext()!=null){//如果链表数为偶数时,快指针走一步就到达尾结点,因此需要做个判断
firstNote=firstNote.getNext();
}
else{
return secondNote;
}
}
return secondNote;
}
定义单向链表ListNote
public class ListNote {
private ListNote NextNote;
private int value;
public ListNote(){
}
public ListNote(int value){
this.value=value;
}
public ListNote getNext(){
return NextNote;
}
public void setNext(ListNote next){
this.NextNote=next;
}
public int getValue(){
return value;
}
public void setValue(int value){
this.value=value;
}
}
时间: 2024-11-05 16:57:57