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

空扰寡人 提交于 2019-12-06 04:56:29

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

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

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