将链表转换为数组,反之亦然 [英] Converting linked list to array and vice-versa

查看:675
本文介绍了将链表转换为数组,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我写了一个链表模板,但想知道如何将列表(在创建之后)转换为数组然后返回到列表?



我尝试了一段简单的代码,但这不正确。



< pre lang =c ++> arr [i] = root-> data;





我也用Google搜索但没有得到一个我真的想要...... :(



所以请帮助....

解决方案

A链表是这样设计的,它不会像数组那样占用连续的内存部分。将LL转换为数组的唯一方法是将数据按元素复制到内存的连续部分,类似于伪代码:



 LinkedList current = root; 
datatype [] array = new array [linked_list_count];
int i = 0;

while(current-> next!= null)
{
array [i] = current-> data;
current = c urrent->接着,
i ++;
}





如果真的是C(不是C ++),它会有点复杂,因为你必须分配正确的内存量,并通过数据类型的大小增加指针值。您还可以创建一个指针数组,并使用每个linkedlist->数据类型的位置填充数组,这更像是链表的浅层副本。


Hi all,

I have written a linked list template but was wondering how I could convert the list (after it is created) to an array and then back into a list?

I tried a simple piece of code but it is not correct.

arr[i] = root->data;



I also googled it but not getting the one which i really want... :(

So please help....

解决方案

A linked list is designed such that it does not occupy a contiguous section of memory like an array does. The only way to convert a LL to an array is to copy the data to a contiguous section of memory element by element, something like this pseudo-code:

LinkedList current = root;
datatype[] array = new array[linked_list_count];
int i = 0;

while (current->next != null)
{
    array[i] = current->data;
    current = current->next; 
    i++;   
}



Its a little more complicated if it truely is C (not C++), since you have to allocate the correct amount of memory and increase the pointer value by the size of the data type. You could also create an array of pointers and just fill the array with the location of each linkedlist->data type which is more like a shallow copy of the linked list.


这篇关于将链表转换为数组,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆