简体   繁体   中英

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?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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