fork download
  1. #include <iostream>
  2. using namespace std;
  3. struct Node {
  4. int data;
  5. Node* next;
  6. Node(int value)
  7. {
  8. data = value;
  9. next = nullptr;
  10. }
  11. };
  12.  
  13. Node* insertAtPosition(Node* head, int position, int data) {
  14. Node* newNode = new Node(data);
  15.  
  16. if (position == 1) {
  17. newNode->next = head;
  18. head = newNode;
  19. return head;
  20. }
  21.  
  22. Node* current = head;
  23.  
  24. for (int i = 1; i < position - 1 && current != nullptr;
  25. ++i) {
  26. current = current->next;
  27. }
  28. if (current == nullptr) {
  29. cout << "Position is out of bounds." << endl;
  30. delete newNode;
  31. return head;
  32. }
  33.  
  34. newNode->next = current->next;
  35. current->next = newNode;
  36. return head;
  37. }
  38.  
  39. Node* deleteNode(Node* head, int position)
  40. {
  41. Node* prev;
  42. Node* temp = head;
  43.  
  44. if (temp == NULL)
  45. return head;
  46.  
  47. if (position == 1) {
  48. head = temp->next;
  49. return head;
  50. }
  51. for (int i = 1; i != position; i++) {
  52. prev = temp;
  53. temp = temp->next;
  54. }
  55.  
  56. if (temp != NULL) {
  57. prev->next = temp->next;
  58. free(temp);
  59. }
  60. else {
  61. cout << "Data not present\n";
  62. }
  63.  
  64. return head;
  65. }
  66.  
  67.  
  68. void printList(Node* head){
  69. while (head != nullptr) {
  70. cout << head->data << " ";
  71. head = head->next;
  72. }
  73. }
  74.  
  75. int main(){
  76.  
  77. Node* head = new Node(1);
  78. head->next = new Node(2);
  79. head->next->next = new Node(3);
  80. head->next->next->next = new Node(4);
  81. head->next->next->next->next = new Node(5);
  82. cout << "linked List : ";
  83. printList(head);
  84. int n;
  85. string s="\n\n1.insertion,\n2.deletion,\nchoose any: ";
  86. while(cout<<s,cin>>n)
  87. {
  88. int data,pos;
  89. cout<<"\nPosition: ";
  90. cin>>pos;
  91. (n-1)? (head = deleteNode(head, pos)):(cout<<"\nData: ",cin>>data,head = insertAtPosition(head, pos, data));
  92. cout << "\nlinked List : ";
  93. printList(head);
  94. }
  95.  
  96. return 0;
  97. }
  98.  
Success #stdin #stdout 0.01s 5284KB
stdin
1
3 5
stdout
linked List : 1 2 3 4 5 

1.insertion,
2.deletion,
choose any: 
Position: 
Data: 
linked List : 1 2 5 3 4 5 

1.insertion,
2.deletion,
choose any: