1. 程式人生 > >java實現---查詢單鏈表的中間節點,要求只能遍歷一次連結串列

java實現---查詢單鏈表的中間節點,要求只能遍歷一次連結串列

  • 定義兩個節點,一個快,一個慢
  • 快的一次走兩步;慢的一次走一步
  • 當快的走到連結串列的最後時,慢的剛好走到一半,即連結串列的中間節點
class ListNode{
    int data;
    ListNode next;
}
public class Link{
    public static void FindMid(ListNode first){
        ListNode fast = first;
        ListNode slow = first;
        while((fast != null)&&(fast.next != null)){
            fast = fast.next.next;
            slow = slow.next;
        }
        System.out.println(slow.data);

    }
    public static void main(String[] args) {
        ListNode n1 = new ListNode();
        ListNode n2 = new ListNode();
        ListNode n3 = new ListNode();
        ListNode n4 = new ListNode();
        ListNode n5 = new ListNode();
        n1.data = 1;
        n2.data = 2;
        n3.data = 3;
        n4.data = 4;
        n5.data = 5;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        FindMid(n1);
    }
}