I am studying algorithms and an exercise asked me to convert a linked list to an array (using pseudo-code), this is what I have done:
convert_LL_array (List, array)
i = 0
current = List.start
while (current != null)
array[i] = current->data
current = current->next
i++
return array
And here is the answer:
convert_LL_array (List, array)
i = 0
current = List.start
while (current->next != null)
array[i] = current->data
current = current->next
i++
return array
Why should I use "current->next" when I compare to "null"? I think that does not add the last element to the array.
Your pseudo-code seems correct,there is nothing wrong with that.As Tim Pointed out that other answer will not work in the case if there is only one element in the linked list.I just want to add that you can check complete code on below link,if you have still have any confusion. 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;
}