首页 > 其他 > 详细

找出链表的中间结点

时间:2015-05-17 12:20:30      阅读:149      评论:0      收藏:0      [点我收藏+]

思路:定义两个快慢指针,快指针一次走两步,慢指针一次走一步,当快指针到达尾结点时,慢指针刚好为中间结点,这里需要区分两种情况,当链表中结点数为奇数时,慢指针刚好到达中间结点;当链表中结点数为偶数时候,中间结点有两个,返回一个。

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;
    }
}

找出链表的中间结点

原文:http://blog.csdn.net/qq_16687803/article/details/45787137

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!