简体   繁体   English

如何从Java中的链表中查找中间值或节点?

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

I have the 50 values in linked list.how to find a middle value or node of linked list? 我在链表中​​有50个值。如何找到链表的中间值或节点?

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....... 谢谢.......

Get 2 references to the same list. 获得2个引用到同一列表。

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.
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 

也许您的团队负责人建议您使用ArrayList而不是LinkedList。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM