Question about #java# : In Java I put the list in the array, but the reading group found that the contents of the array were suddenly in reverse order

dqxiaoying 注册会员
2023-02-25 20:04

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > if you are in the list, in turn, in the process of the array without exception, the reverse is likely due to the content of the inside array when you traverse the list, The list elements were not added to the array in the correct order.

If you want to preserve the order of the list elements in the array, you can use a variable to record the array subscripts and add the elements to the array in the order of the subscripts as you traverse the list.

Here is an example code where the listed node is of type ListNode and the array is of type ListNode[] :

ListNode head = ...;  // 假设链表的头节点为head
int size = ...;      // 假设链表的长度为size
ListNode[] array = new ListNode[size];

// 遍历链表,并将元素添加到数组中
int index = 0;
ListNode cur = head;
while (cur != null) {
    array[index] = cur;
    cur = cur.next;

// 遍历数组,按照顺序打印元素
for (int i = 0; i < size; i++) {

In this example code, we walk through the list and add the nodes of the list to the array in turn. As we traverse the list, we use a variable index to record the index of the element we are currently adding to the array, incrementing index by one each time we add the element to the array. This way, we can ensure that the elements in the array are in the same order as those in the list.

About the Author

Question Info

Publish Time
2023-02-25 20:04
Update Time
2023-02-25 20:04

Related Question


AspenTech InfoPlus 21如何选择NULL值?

Using multiprocessing and multithreading together to stream data in python

linux grep,stat,xargs指令求解!



使用nginx-ingress http可以工作,但https不能在selfhost kubernetes上


返回key from object NOT array JavaScript