fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node{
  5. int data;
  6. Node *next, *prev;
  7. Node(int val)
  8. {
  9. data = val;
  10. next = NULL;
  11. prev = NULL;
  12. }
  13. };
  14. Node *head = NULL, *tail= NULL;
  15. void print()
  16. {
  17. Node *temp = head;
  18. while(temp!=NULL)
  19. {
  20. cout<<temp->data<<"->";
  21. temp=temp->next;
  22. }
  23. cout<<"null"<<"\n";
  24. }
  25. void display_reverse(){
  26. Node *temp = tail;
  27. while(temp!=NULL)
  28. {
  29. cout<<temp->data<<"->";
  30. temp = temp->prev;
  31. }
  32. cout<<"null"<<"\n";
  33. }
  34.  
  35. void insert(int val)
  36. {
  37. if(head == NULL)
  38. {
  39. head = new Node(val);
  40. tail = head;
  41. return;
  42. }
  43. Node *temp = new Node(val);
  44. tail->next = temp;
  45. temp -> prev = tail;
  46. tail = temp;
  47. }
  48.  
  49.  
  50. int main() {
  51. int n;
  52. cin>>n;
  53. while(n--)
  54. {
  55. int j;
  56. cin>>j;
  57. insert(j);
  58. }
  59. print();
  60. display_reverse();
  61. return 0;
  62. }
Success #stdin #stdout 0s 4372KB
stdin
5
1 2 3 4 5
stdout
1->2->3->4->5->null
5->4->3->2->1->null