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 *createLinkedList(int arr[], int size);
  10. void print(struct Node *head);
  11. void insert(struct Node *head, int pos, int value);
  12.  
  13. int main() {
  14. int a[] = {15, 30, 45, 60, 100};
  15. struct Node *head = NULL;
  16. head = createLinkedList(a, 5);
  17. print(head);
  18. insert(head, 2, 555);
  19. insert(head,3,56);
  20. insert(head,0,97);
  21. print(head);
  22. return 0;
  23. }
  24.  
  25. void insert(struct Node *head, int pos, int value) {
  26. struct Node *temp = head;
  27. int count = 0;
  28. while (temp != NULL) {
  29. count++;
  30. if (count == pos) {
  31. struct Node *newnode = (struct Node*)malloc(sizeof(struct Node));
  32. newnode->data = value;
  33. newnode->next = temp->next;
  34. temp->next = newnode;
  35. return;
  36. }
  37. temp = temp->next;
  38. }
  39. }
  40.  
  41. void print(struct Node *head) {
  42. struct Node *temp = head;
  43. while (temp != NULL) {
  44. printf("%d ", temp->data);
  45. temp = temp->next;
  46. }
  47. printf("\n");
  48. }
  49.  
  50. struct Node *createLinkedList(int arr[], int size) {
  51. struct Node *head = NULL;
  52. struct Node *temp = NULL;
  53. struct Node *current = NULL;
  54. int i;
  55. for (i = 0; i < size; i++) {
  56. temp = (struct Node*)malloc(sizeof(struct Node));
  57. temp->data = arr[i];
  58. temp->next = NULL;
  59. if (head == NULL) {
  60. head = temp;
  61. current = temp;
  62. } else {
  63. current->next = temp;
  64. current = current->next;
  65. }
  66. }
  67. return head;
  68. }
  69.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
15 30 45 60 100 
15 30 555 56 45 60 100