fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node {
  4. int val;
  5. struct node *next;
  6.  
  7. };
  8.  
  9. struct list {
  10. struct node* first;
  11. struct node* last;
  12. };
  13.  
  14. struct list* makelist() {
  15. struct list *l;
  16. l = (struct list*)malloc(sizeof(struct list));
  17. l->first = NULL;
  18. l->last = NULL;
  19. return l;
  20. }
  21. void freelist(struct list* l) {
  22. if (l->first == NULL) {
  23. free(l);
  24. return;
  25. }
  26. struct node *temp = l->first, *nextNode;
  27. while (temp != NULL)
  28. {
  29. nextNode = temp->next;
  30. free(temp);
  31. temp = nextNode;
  32. }
  33.  
  34. free(l);
  35. }
  36. void search(struct list*l,int cou,int sindex){
  37. if(sindex>cou){
  38. printf("Index out of range");
  39. }
  40. else{
  41. struct node* temp=l->first;
  42. while(temp!=NULL){
  43. for(int i=0;cou;i++){
  44. if(i==sindex){
  45. printf("Item found! %d",temp->val);
  46. }
  47. else
  48. temp=temp->next;
  49. }
  50. }
  51. }
  52. }
  53.  
  54. int addnode(struct list* l, int v) {
  55. struct node* n;
  56. int cou = 0;
  57. n = (struct node*)malloc(sizeof(struct node));
  58. n->val = v;
  59. n->next = NULL;
  60. cou+=1;
  61. if (l->first == NULL) {
  62. l->first = l->last = n;
  63. } else {
  64. l->last->next = n;
  65. l->last = n;
  66. }
  67. return cou;
  68. }
  69. void printlist(struct list* l) {
  70. struct node* temp = l->first;
  71. printf("Linked List: ");
  72. while (temp != NULL) {
  73. printf("%d -> ", temp->val);
  74. temp = temp->next;
  75. }
  76. printf("NULL\n");
  77. }
  78. int main() {
  79. int cou=0,sindex;
  80. int noOfNode;
  81. char ope;
  82. struct list *l = makelist();
  83. printf("Kindly give the number of nodes to be added : ");
  84. scanf("%d",&noOfNode);
  85. for(int i=0;i<noOfNode;i++){
  86. int num;
  87. printf("Provide the number to be added to the List : ");
  88. scanf("%d",&num);
  89. cou = addnode(l,num);
  90. }
  91. printf("Kindly provide the instruction to perform else type any other key \n P : Print\n K: Search\n");
  92. scanf(" %c",&ope);
  93. if(ope=='P')
  94. printlist(l);
  95. else if(ope=='K'){
  96. printf("Kindly give the Kth element index : ");
  97. scanf("%d",&sindex);
  98. search(l,cou,sindex-1);
  99. }
  100. freelist(l);
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 5288KB
stdin
2
3
4
P
stdout
Kindly give the number of nodes to be added : Provide the number to be added to the List : Provide the number to be added to the List : Kindly provide the instruction to perform else type any other key 
 P : Print
 K: Search
Linked List: 3 -> 4 -> NULL