how to find middle node in singly linked list without traversal?

狂风中的少年 提交于 2019-12-07 01:26:11

问题


how to find middle node in singly linked list without traversal ?

is it possible in first place ?

In One traversal I Use the traditional method of using 2 pointers one which jump's 2 positions and other which jump's one position ..is there any other approach to find middle node in one traversal


回答1:


No, it's not possible. The addresses of the nodes are arbitrary, so there's no way of knowing them without traversing them.




回答2:


public void findMiddleNode() {
    Node n1 = headNode;
    Node n2 = headNode;
    while(n2.getNext() != null && n2.getNext().getNext()!= null) {
        n1 = n1.getNext();
        n2 = n2.getNext().getNext();
    }

    System.out.println("middle node is "+n1.getKey());
}



回答3:


Yes, you can if you are controlling all aspects of the list's adds and deletes.

If you maintain a reference to what is considered to be the midway node during add or deletes then it can be done. There are couple cases that have to be handled. In addition, there are scenarios such as where there is an even number of elements to consider. What will be the midway node in such a situation? ect.. ect..

So you really aren't finding the midway node, but rather, tracking it.




回答4:


List list = new LinkedList();
    for (int i = 0; i < 50; i++) {
    list.add(String.valueOf(i));
}

int end = list.size() - 1;
int start = 0;
while (start > end) {
    start++;
    end--;
}
if(start == end) //The arrays length is an odd number and you found the middle
    return start;
else //The arrays length is an even number and there really isn't a middle
    //Do something else here because you have an even number 

I saw this code on some other solution page... Is this not another method where the list is being singly traversed!?




回答5:


import java.util.LinkedList;
import java.util.List;


public class consoleApp 
{
    public static void main(String[] args)
    {
        List list = new LinkedList();
        for (int i = 0; i < 50; i++) 
        {
            list.add(String.valueOf(i));
        }

        int end = list.size();

        int start = 0;
        while (start< end) 
        {
            start++;
            end--;
        }

        if(start == end) 
            System.out.println(start);
    }
}


来源:https://stackoverflow.com/questions/4707128/how-to-find-middle-node-in-singly-linked-list-without-traversal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!