Java – how to get to the middle of a singular linked list in an iteration?

Recently, I was asked a question, how do we get to the middle of the list in an iteration in a separate linked list

A --> B --> C --> D (even nodes)

To do this, it should return the address to B

A --> B --> C (odd nodes)

For this, it should also return the address to B

There is a solution where two pointers move once and the other two times, but it doesn't seem to work here

LinkedList p1,p2;

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

}

System.out.print("middle of the node" + p1.data); //This does not give accurate result in odd and even

If anyone has done this before, please help

Solution

Unless you successfully advance P2 twice, you cannot advance P1; Otherwise, if the list length is 2, both end up at the end (and you indicate that even the length list should be rounded toward the beginning)

So:

while ( p2.next != null ) {
    p2 = p2.next;
    if (p2.next != null) {
        p2 = p2.next;
        p1 = p1.next;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>