fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Node {
  5. int data;
  6. struct Node *next;
  7. };
  8.  
  9. struct Node *head = NULL;
  10.  
  11. /* Function Prototypes */
  12. void insertEnd(int);
  13. void insertBeginning(int);
  14. void insertAtPosition(int, int);
  15. void display();
  16.  
  17. /* Insert at end */
  18. void insertEnd(int value) {
  19. struct Node *newNode = malloc(sizeof(struct Node));
  20. newNode->data = value;
  21. newNode->next = NULL;
  22.  
  23. if (head == NULL) {
  24. head = newNode;
  25. return;
  26. }
  27.  
  28. struct Node *temp = head;
  29. while (temp->next != NULL)
  30. temp = temp->next;
  31.  
  32. temp->next = newNode;
  33. }
  34.  
  35. /* Insert at beginning */
  36. void insertBeginning(int value) {
  37. struct Node *newNode = malloc(sizeof(struct Node));
  38. newNode->data = value;
  39. newNode->next = head;
  40. head = newNode;
  41. }
  42.  
  43. /* Insert at any position */
  44. void insertAtPosition(int value, int pos) {
  45. if (pos < 1) {
  46. printf("Invalid position\n");
  47. return;
  48. }
  49.  
  50. if (pos == 1) {
  51. insertBeginning(value);
  52. return;
  53. }
  54.  
  55. struct Node *temp = head;
  56. for (int i = 1; i < pos - 1 && temp != NULL; i++)
  57. temp = temp->next;
  58.  
  59. if (temp == NULL) {
  60. printf("Invalid position\n");
  61. return;
  62. }
  63.  
  64. struct Node *newNode = malloc(sizeof(struct Node));
  65. newNode->data = value;
  66. newNode->next = temp->next;
  67. temp->next = newNode;
  68. }
  69.  
  70. /* Display list */
  71. void display() {
  72. struct Node *temp = head;
  73. while (temp != NULL) {
  74. printf("%d -> ", temp->data);
  75. temp = temp->next;
  76. }
  77. printf("NULL\n");
  78. }
  79.  
  80. int main() {
  81. int choice, value, pos;
  82.  
  83. while (1) {
  84. printf("\n1. Insert End\n");
  85. printf("2. Insert Beginning\n");
  86. printf("3. Insert Position\n");
  87. printf("4. Display\n");
  88. printf("0. Exit\n");
  89. printf("Enter your choice: ");
  90. scanf("%d", &choice);
  91.  
  92. switch (choice) {
  93. case 1:
  94. printf("Enter value: ");
  95. scanf("%d", &value);
  96. insertEnd(value);
  97. break;
  98. case 2:
  99. printf("Enter value: ");
  100. scanf("%d", &value);
  101. insertBeginning(value);
  102. break;
  103. case 3:
  104. printf("Enter value: ");
  105. scanf("%d", &value);
  106. printf("Enter position: ");
  107. scanf("%d", &pos);
  108. insertAtPosition(value, pos);
  109. break;
  110. case 4:
  111. display();
  112. break;
  113. case 0:
  114. exit(0);
  115. default:
  116. printf("Invalid choice\n");
  117. }
  118. }
  119. return 0;
  120. }
  121.  
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
1. Insert End
2. Insert Beginning
3. Insert Position
4. Display
0. Exit
Enter your choice: