如何从Java中的链表中查找中间值或节点? [英] How to find a middle value or node from linked list in java?
本文介绍了如何从Java中的链表中查找中间值或节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有链表的 50 个值.如何找到链表的中间值或节点?
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?
谢谢....
推荐答案
获取2个对同一列表的引用.
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.
这篇关于如何从Java中的链表中查找中间值或节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文