How to find a middle value or node from linked list in java?

跟風遠走 提交于 2019-12-22 13:40:09

问题


I have the 50 values in linked list.how to find a middle value or node of linked list?

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

int size = list.size();
int middle = (size / 2);
System.out.println(list.get(middle).toString());...

i got an answer like this.... But my team leader said to find in another way? Is there any other built in method to iterate in linked list?i tried ...but i dint get any built in method for finding middle value...And or can u any one suggest another logic to find the value of middle node in linke list?

thank you.......


回答1:


Get 2 references to the same list.

In a single loop:
Advance the 1st list 2 nodes at a time.
Advance the 2nd list 1 node at a time.
Loop until the 1st loop reaches the end.



回答2:


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 



回答3:


Maybe your team lead was suggesting you use an ArrayList rather than a LinkedList.

List<String> list = new ArrayList<String>(50);


来源:https://stackoverflow.com/questions/5150843/how-to-find-a-middle-value-or-node-from-linked-list-in-java

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