链表转数组(伪代码)
Convert linked list to array (pseudo-code)
我正在学习算法,有一个练习要求我将链表转换为数组(使用伪代码),这就是我所做的:
convert_LL_array (List, array)
i = 0
current = List.start
while (current != null)
array[i] = current->data
current = current->next
i++
return array
答案如下:
convert_LL_array (List, array)
i = 0
current = List.start
while (current->next != null)
array[i] = current->data
current = current->next
i++
return array
与"null"比较时为什么要使用"current->next"?我认为这不会将最后一个元素添加到数组中。
你的伪代码似乎是正确的,that.As Tim 没有错 指出如果 linked [=] 中只有一个元素,其他答案将不起作用15=] 只是想补充一点,如果您仍然有任何困惑,可以查看下面的完整代码 link。
https://ideone.com/qN1HBZ
struct ListNode{
int data;
struct ListNode* next;
ListNode(int val):data(val),next(NULL){}
};
void convertLLtoArray(ListNode* head, vector<int>&arr){
//if there is no element then return
if(head==NULL)return;
//crawling pointer
ListNode* crawl = head;
//iterate until list pointer become NULL
while(crawl!=NULL){
arr.push_back(crawl->data);
crawl = crawl->next;
}
return;
}
我正在学习算法,有一个练习要求我将链表转换为数组(使用伪代码),这就是我所做的:
convert_LL_array (List, array)
i = 0
current = List.start
while (current != null)
array[i] = current->data
current = current->next
i++
return array
答案如下:
convert_LL_array (List, array)
i = 0
current = List.start
while (current->next != null)
array[i] = current->data
current = current->next
i++
return array
与"null"比较时为什么要使用"current->next"?我认为这不会将最后一个元素添加到数组中。
你的伪代码似乎是正确的,that.As Tim 没有错 指出如果 linked [=] 中只有一个元素,其他答案将不起作用15=] 只是想补充一点,如果您仍然有任何困惑,可以查看下面的完整代码 link。 https://ideone.com/qN1HBZ
struct ListNode{
int data;
struct ListNode* next;
ListNode(int val):data(val),next(NULL){}
};
void convertLLtoArray(ListNode* head, vector<int>&arr){
//if there is no element then return
if(head==NULL)return;
//crawling pointer
ListNode* crawl = head;
//iterate until list pointer become NULL
while(crawl!=NULL){
arr.push_back(crawl->data);
crawl = crawl->next;
}
return;
}