其他分享
首页 > 其他分享> > 寻找无环单链表的中点

寻找无环单链表的中点

作者:互联网

/**
 * 寻找无环单链表的中点
 */
public class Test4 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(6);
        System.out.println(calc(head).val);
    }


    public static ListNode calc(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

标签:head,单链,ListNode,无环,fast,next,slow,new,中点
来源: https://blog.csdn.net/qq_36986015/article/details/113776938