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