fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node
  5. {
  6. int data;
  7. node *next = nullptr;
  8. };
  9.  
  10. node *list = nullptr;
  11.  
  12. void insertFront()
  13. {
  14. int value;
  15.  
  16. //cout << "ENTER A VALUE=";
  17. cin >> value;
  18.  
  19. list = new node{value, list};
  20. }
  21.  
  22. void display()
  23. {
  24. for(node *p = list; p != nullptr; p = p->next)
  25. {
  26. cout << p->data << " ";
  27. }
  28. cout << endl;
  29. }
  30.  
  31. void insertSpec()
  32. {
  33. int number, value;
  34.  
  35. //cout << "Enter the node number after which you want to enter a new node=";
  36. cin >> number;
  37.  
  38. if (number < 1)
  39. {
  40. cout << "INVALID NODE NUMBER!" << endl;
  41. return;
  42. }
  43.  
  44. node **p = &list;
  45. int n = number;
  46.  
  47. while (*p != nullptr && n > 0)
  48. {
  49. p = &((*p)->next);
  50. --n;
  51. }
  52.  
  53. if (n > 0)
  54. {
  55. cout << "YOU CANNOT PUT A NODE AFTER " << number << endl;
  56. return;
  57. }
  58.  
  59. //cout << "ENTER THE VALUE YOU WANT TO ADD=";
  60. cin >> value;
  61.  
  62. *p = new node{value, *p};
  63. }
  64.  
  65. int main()
  66. {
  67. int choice;
  68.  
  69. /*
  70.   cout << "1) Insert at front" << endl;
  71.   cout << "5) Insert at specified place" << endl;
  72.   cout << "9) Display" << endl;
  73.   cout << "99) Exit" << endl << endl;
  74. */
  75.  
  76. do
  77. {
  78. //cout << "Your choice:";
  79. cin >> choice;
  80.  
  81. switch (choice)
  82. {
  83. case 1:
  84. insertFront();
  85. break;
  86.  
  87. case 5:
  88. insertSpec();
  89. break;
  90.  
  91. case 9:
  92. display();
  93. break;
  94. }
  95. }
  96. while (choice != 99);
  97.  
  98. cout << "PROGRAM TERMINATED :)";
  99.  
  100. return 0;
  101. }
Success #stdin #stdout 0.01s 5436KB
stdin
1 3
1 2
1 1
9
5 5
5 3 4
9
99
stdout
1 2 3 
YOU CANNOT PUT A NODE AFTER 5
1 2 3 4 
PROGRAM TERMINATED :)