java中如何从链表中找到中间值或节点?

发布于 2024-10-19 19:39:22 字数 406 浏览 1 评论 0原文

我的链表中有 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 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.......

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

错爱 2024-10-26 19:39:22

获取对同一列表的 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.

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.
謌踐踏愛綪 2024-10-26 19:39:22
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 
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 
随梦而飞# 2024-10-26 19:39:22

也许您的团队领导建议您使用 ArrayList 而不是 LinkedList。

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

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

List<String> list = new ArrayList<String>(50);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文