Regarding finding the middle element of linked list

后端 未结 5 1619
轮回少年
轮回少年 2021-02-04 20:19

I am following the below approach to calculate the middle element from the linked list , but I want is there any built in method or any other approach which can als

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 20:51

    The basic algorithm would be

    • Take two pointers

    • Make both pointing to first node

    • Increment first with two nodes and second with one, at a time.

    • Loop until the 1st loop reaches the end. At this point, the 2nd will be at the middle.

    Example:-

    while ( p2.next != null ) {
        p2 = p2.next;
        if (p2.next != null) {
            p2 = p2.next;
            p1 = p1.next;
        }
    }
    

    It will definitely work in odd case, for even case you need to check one more condition if first point is allowed to move next but not next to next then both pointers will be at middle you need to decide which to take as middle.

提交回复
热议问题