fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Node{
  5. public:
  6. int data;
  7. Node *next;
  8. Node(int x=0){
  9. this->data = x;
  10. this->next = nullptr;
  11. }
  12. };
  13. class LinkedList{
  14. private:
  15. Node *HEAD;
  16. public:
  17. LinkedList(){
  18. HEAD=nullptr;
  19. }
  20. void insertAtFirstPosition(int x){
  21. Node *newNode = new Node(x);
  22. newNode->next = HEAD;
  23. HEAD = newNode;
  24. }
  25. void insertAtAnyPosition(int key, int k){
  26. if(k<1){
  27. cout << "Invalid Position"<<endl;
  28. return;
  29. }
  30. Node *newNode = new Node(key);
  31. if(k==1){
  32. newNode ->next=HEAD;
  33. HEAD=newNode;
  34. return;
  35. }
  36. int counter = 1;
  37. Node *current;
  38. current = HEAD;
  39. while(current != nullptr && counter <(k-1)){
  40. current = current->next;
  41. counter++;
  42. }
  43. if(current == nullptr){
  44. cout << "Invalid Position"<<endl;
  45. delete newNode;
  46. return;
  47. }
  48. newNode->next=current->next;
  49. current->next=newNode;
  50. return;
  51.  
  52. }
  53. void print(){
  54. Node *current;
  55. current = HEAD;
  56. while(current!=nullptr ){
  57. cout<<current->data;
  58. cout<<" -> ";
  59. current = current->next;
  60. }
  61. cout<<" NULL"<<endl;
  62. }
  63. };
  64. int main()
  65. {
  66. LinkedList myList;
  67. myList.insertAtFirstPosition(2);
  68. myList.print();
  69. myList.insertAtAnyPosition(3,2);
  70. myList.print();
  71. myList.insertAtAnyPosition(10,3);
  72. myList.print();
  73. myList.insertAtAnyPosition(5,2);
  74. myList.print();
  75. myList.insertAtAnyPosition(15,12);
  76. myList.print();
  77. return 0;
  78. }
  79.  
  80.  
  81.  
  82.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
2 ->  NULL
2 -> 3 ->  NULL
2 -> 3 -> 10 ->  NULL
2 -> 5 -> 3 -> 10 ->  NULL
Invalid Position
2 -> 5 -> 3 -> 10 ->  NULL