Converting a linked list to an array (pseudo-code)

I study algorithms, and the exercise asked me to convert a linked list to an array (using pseudocode), here is what I did:

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 compared to "null"? I think this does not add the last element to the array.

+4
source share
1 answer

Your pseudo-code seems correct, there is nothing wrong with that. As Tim said, another answer will not work if there is only one item in the linked list. I just want to add that you can check the full code below the link if you still have 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; } 
+1
source

All Articles