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