fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node {
  5. int data;
  6. Node* prev;
  7. Node* next;
  8. };
  9.  
  10. int main() {
  11. // existing list
  12. Node* head = new Node{10, NULL, NULL};
  13. head->next = new Node{20, head, NULL};
  14. head->next->next = new Node{30, head->next, NULL};
  15. head->next->next->next= new Node{45,head->next->next,NULL};
  16.  
  17. // ============= INSERT AT END =============
  18. Node* temp = head;
  19.  
  20. // move to last node
  21. while(temp->next != NULL) {
  22. temp = temp->next;
  23. }
  24.  
  25. // create new node at end
  26. Node* last = new Node{40, temp, NULL};
  27. temp->next = last;
  28. // =========================================
  29.  
  30. // print forward
  31. temp = head;
  32. while(temp != NULL) {
  33. cout << temp->data << " ";
  34. temp = temp->next;
  35. }
  36.  
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
10 20 30 45 40