fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct ListNode{
  6. int data;
  7. struct ListNode* next;
  8. ListNode(int val):data(val),next(NULL){}
  9. };
  10.  
  11.  
  12. void convertLLtoArray(ListNode* head, vector<int>&arr){
  13. //if there is no element then return
  14. if(head==NULL)return;
  15. //crawling pointer
  16. ListNode* crawl = head;
  17. //iterate until list pointer become NULL
  18. while(crawl!=NULL){
  19. arr.push_back(crawl->data);
  20. crawl = crawl->next;
  21. }
  22. return;
  23. }
  24.  
  25. int main() {
  26. ListNode* head;
  27. ListNode* node1 = new ListNode(1);
  28. ListNode* node2 = new ListNode(2);
  29. ListNode* node3 = new ListNode(3);
  30. head = node1;
  31. node1->next = node2;
  32. node2->next = node3;
  33. vector<int>arr;
  34. convertLLtoArray(head,arr);
  35. for(int i=0;i<arr.size();i++){
  36. cout<<arr[i]<<" ";
  37. }
  38. return 0;
  39. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
1 2 3