Jun 22, 2014 at 2:10pm UTC
sequential search(search and insertion)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include <iostream>
using namespace std;
struct node
{
int key;
int record;
node *link;
};
typedef struct node* list;
void print(list head)
{
int i=1;
list temp=head;
cout<<"\nThe records and their associated keys are\n" ;
cout<<"i" <<"\t" <<"key" <<"\t" <<"record" <<endl;
while (temp!=NULL)
{
cout<<i<<"\t" <<temp->key<<"\t" <<temp->record<<"\n" ;
i++;
temp=temp->link;
}
}
void searchAndInsert(list *head,int key_value)
{
int rec_value;
list temp,s;
if (*head==NULL)
{
temp=new node;
cout<<"\nEnter record : " ;
cin>>rec_value;
temp->record=rec_value;
temp->key=key_value;
temp->link=NULL;
*head=temp;
return ;
}
temp=(*head);
while (temp!=NULL && (temp->key)!=key_value)
{
s=temp;
temp=temp->link;
//cout<<"ji";
}
if (temp!=NULL)
{
cout<<"\nrecord found" ;
}
else
{
temp=new node;
cout<<"\nEnter record : " ;
cin>>rec_value;
temp->record=rec_value;
temp->key=key_value;
s->link=temp;
temp->link=NULL;
}
}
int main()
{
int key_value,n;
list head=NULL;
while (1)
{
cout<<"Enter the key you want to search :" ;
cin>>key_value;
searchAndInsert(&head,key_value);
print(head);
cout<<"\n\nanother search?(1/0) : " ;
cin>>n;
}
}
Last edited on Jun 23, 2014 at 3:32am UTC
Jun 22, 2014 at 3:41pm UTC
Switch && operands. Checking for null pointer should be done first.
Jun 22, 2014 at 4:21pm UTC
thnx alot :)
Last edited on Jun 22, 2014 at 4:24pm UTC
Jun 22, 2014 at 4:24pm UTC
If the pointer is NULL it isn't even possible to evaluate the other operand. That's why it must be done first.
Jun 22, 2014 at 4:25pm UTC
temp->key
can crash if you will try to apply it to the null pointer.
If you make temp != NULL
it wil stop if it will evaluate to false (if temp is a null pointer) and will not execute second part, saving you from undefined behavior.
Jun 22, 2014 at 4:33pm UTC
plzz hav a look..the first while loop is not working
Jun 22, 2014 at 4:35pm UTC
Could you please explain what is meant by "not working".
Jun 22, 2014 at 4:35pm UTC
thnx for the help...cud u plz help me with my first while loop also
Jun 22, 2014 at 4:40pm UTC
Run time error caused by trying to de-reference a NULL pointer?
Jun 22, 2014 at 4:54pm UTC
compare lines 31-37 and 53-58. You forgot to set one field.