View Single Post
Old 07-02-2004, 05:52 AM   #1 (permalink)
Banan
Registered User
 
Banan's Avatar
 
Join Date: Jul 2004
Posts: 1
Banan is on a distinguished road
Retrieve Nodes from Sorted Linked Lists

Hello,

What I am trying to in this program is to input number, display them sorted, input another set of numbers and tell what numbers are in the list and which arent.
I have my insert function working just fine, I need a little help on Retrieve function. How to make it work... ?

Please help, thanks.

#include <iostream>
#include<string>
using namespace std;
typedef int ItemType;

struct Node
{ ItemType item;
Node *next;
}; // end struct



void linkedListInsert(Node*& headPtr,
ItemType newItem)
{
if ((headPtr == NULL) || (newItem < headPtr->item))
{ // base case: insert newItem at beginning
// of the linked list to which headPtr points
Node *newPtr = new Node;
if (newPtr == NULL)
cout<< "ListException: insert cannot allocate memory";
else
{ newPtr->item = newItem;
newPtr->next = headPtr;
headPtr = newPtr;
// cout<<newItem;
} // end if
}
else

linkedListInsert(headPtr->next, newItem);

}


void retrieve(Node *head1, Node *head2, ItemType newItem,int count)// inputted count, so with each recursion count is increasing.
{
Node *p1=head1, *p2=head2; // head1 points to insert list, head2 to retrieve list.

count=1; // initialized

if(p1->item==p2->item)// if the numbers p1 and p2 are pointing to are equal - base case

{
cout<<p1->item<<"is in position"<<count<<endl;// I output the number
p1->next; // the insert list is traversing to check if there are more numbers like the first node in p2.
count++
}
else
{

retrieve( head1=NULL, head2->next, newItem,count++);// traverses the retrieve list and sets head to the 1st node

}

}


int main ()

{
ItemType number;
int count;
Node * head1=NULL;
Node *head2=NULL;

while ( number != 0 ) {

cout<<"Please enter numbers to be inserted,(0 to end): "<<endl;
cin>>number;
linkedListInsert(head1,number);

}

cout<<"The list is:"<<endl;

while(head1 !=NULL)

{

cout<<head1->item;
head1 = head1->next ;


} cout<<endl;
number=1; //so that it enters the loop
while(number!=0)
{
cout<<"Please enter the numbers to be retrieved (0 to end): "<<endl;
cin>>number;
retrieve(head1,head2,number,count);
}


return 0;
}
Banan is offline   Reply With Quote