How to go to the middle of a single linked list in one iteration?

Recently I was asked one question, what is in the only linked list, how do we go to the middle of the list in one iteration.

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

To do this, it must return an address that points to B

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

for this, it should also return an address that points to B

There is one solution consisting of two pointers: one move once, and the other two times, but it does not 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

Please help if someone has done this before.

+3
source share
6 answers

p1, p2 ; , 2, ( , ).

:

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

0

1 node

2 node , , node

3, , .

:

, , , , ,

alt text

+6

, , , . - O (n), O (n/2)?

EDIT: O (1), . ysth .

:

LinkedList list = ...
int size = list.size();
int middle = (size / 2) + (size % 2 == 0 ? 0 : 1) - 1; //index of middle item
Object o = list.get(middle);  //or ListIterator it = list.listIterator(middle);
+1

The decision to take two pointers and one half speed move should work fine. Most likely, this is not a solution, and your actual implementation is a problem. Post more details about your implementation.

0
source
static ListElement findMiddle(ListElement head){
    ListElement slower = head;
    ListElement faster = head;
    while(faster.next != null && faster.next.next !=null ){
        faster = faster.next.next;
        slower = slower.next;
    } 
    return slower;
}
0
source
public static Node middle(Node head){

    Node slow=head,fast=head;
    while(fast!=null& fast.next!=null && fast.next.next!=null){

         slow=slow.next;
         fast=fast.next.next;                   
    } 


    if(fast!=null && fast.next!=null){
        slow=slow.next;
    }


    return slow;

} 
0
source

Source: https://habr.com/ru/post/1781652/


All Articles