Hi guys;
I wrote a function that inserts a new integer in the ordered link-list. If the number to insert exist in the link-list then the insertion WILL not take place, instead a message “Number To Insert Exists !!” will be produced. Can some1 help me to find out the error that makes the looping print ????
#include <iostream>
using namespace std;
typedef int value;
struct node {
value num;
node *next;
};
typedef struct node *nodePtr;
void insert(nodePtr &head, value val);
int getNumber ();
bool check (nodePtr head, value val);
void print (nodePtr head);
int main()
{
nodePtr head;
head = NULL;
value num;
//asssume only postive numbers are inserted
do {
num = getNumber();
if (num > 0)
insert(head, num);
print(head);
}while (num > 0);
system("pause");
return 0;
}
int getNumber ()
{
int num;
cout<<"Enter Number to be inserted: "<<flush;
cin>>num;
return num;
}
void insert(nodePtr &head, value val)
{
nodePtr temp;
//inserting into an empty list
if (head == NULL)
{
temp = new node;
temp->num = val;
temp->next = NULL;
head = temp;
}
else
if (!check(head, val))
{
temp = new node;
temp->num = val;
temp->next = NULL;
// find location
nodePtr findFst = head;
nodePtr findSec = head;
while (findFst->next != NULL && findFst->num < val)
{
findSec = findFst;
findFst = findFst->next;
}
if (findFst == head) //inserting in begining
{
temp->next = findFst;
findSec->next = temp;
}
else if (findSec->num < val && findFst->num >val)//inserting in the middle
{
temp->next = findFst;
findFst->next = temp;
}
else //insertion at the end
findFst->next = temp;
}
else
cout<<"Number to be inserted exists"<<endl;
}
bool check (nodePtr head, value val)
{
while (head != NULL){
if (head->num == val)
return true;
head = head->next;
}
return false;
}
void print (nodePtr head)
{
while (head != NULL)
{
cout<<head->num<<" / ";
head = head->next;
}
cout<<endl;
}