Advertisement
sanpai

Searching for an element in the linked list

Aug 13th, 2012
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<malloc.h>
  3.  
  4. struct node * addelement(struct node * ,int);
  5. void display(struct node *);
  6. void search(struct node *, int);
  7.  
  8. struct node
  9.  
  10. {
  11.  
  12. int data;
  13. struct node *ptr;
  14. };
  15.  
  16. int main()
  17. {
  18.  
  19. int a,b,num;
  20. struct node *head;
  21. printf(" \n Enter the elements to be added to the linked list ");
  22. scanf("%d %d",&a,&b);
  23. head=NULL;
  24. head=addelement(head,a);
  25. head=addelement(head,b);
  26. display(head);
  27. printf("\n The element to be searched in the list ");
  28. scanf("%d",&num);
  29. search(head,num);
  30. }
  31.  
  32. struct node * addelement(struct node *head,int info)
  33. {
  34.  
  35. struct node *newnode;
  36. newnode=(struct node *)malloc(sizeof(struct node));
  37. newnode->data=info;
  38. if(head==NULL)
  39. {
  40.  
  41. newnode->ptr=NULL;
  42.  
  43. return newnode;
  44. }
  45. else
  46.  
  47. {
  48. newnode->ptr=head;
  49. return newnode;
  50. }
  51. }
  52.  
  53. void display(struct node *head)
  54. {
  55.  
  56. while(head!=NULL)
  57. {
  58. printf("%d\t",head->data);
  59. head=head->ptr;
  60. }
  61. }
  62.  
  63. void search(struct node *head,int x)
  64.  
  65. { int flag=0;
  66. while(head!=NULL)
  67. {
  68.  
  69. if(head->data==x)
  70. {
  71. flag=1;
  72. break;
  73. }
  74. else
  75. {
  76.  
  77. head=head->ptr;
  78. }
  79. }
  80.  
  81. if(flag==1)
  82.  
  83. printf("\n The element %d is found in the list",x);
  84.  
  85. else
  86.  
  87. printf("\n The element is not present in the list \n");
  88.  
  89. }
  90. 41,1-8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement