hi
im havin a problem w/ printing a linked list.
my program reads two input files and makes two linked lists out of them, and apend the lists and print it out.
my input files look like this:
1 2 3 4 5 (input1)
11 22 33 44 (input2)
here's my program. i think everythin is working well except printing or may be getNext function. Please help me out. thanks.
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
#define FILE_1 "input1.txt"
#define FILE_2 "input2.txt"
struct NODE
{
int data;
NODE *link;
};
struct LIST
{
NODE *head;
NODE *pos;
int count;
};
void build (LIST &list, char *filename);
//void printList (LIST list);
void append (LIST &list1, LIST &list2);
bool searchList (LIST list, NODE *&pPre,
NODE *&pLoc, int target);
bool getNext(LIST &list, int fromWhere, int &dataOut);
bool insertNode (LIST &list, NODE *&pPre, int num);
int main (void)
{
LIST list1;
LIST list2;
build (list1 , FILE_1);
// printList (list1);
build (list2 , FILE_2);
// printList (list2);
append (list1 , list2);
// printList (list1);
cout << "\n\nTotal number of nodes = "<< list1.count << endl;
return 0;
}
void build (LIST &list, char *filename)
{
ifstream infile;
NODE *pPre;
NODE *pLoc;
int num;
bool found;
infile.open(filename, ios::in);
if (!infile)
{
cerr << "\n\aCannot open " << filename << endl;
abort();
}
list.head = NULL;
list.count = 0;
while (infile>>num)
{
found = searchList(list, pPre, pLoc, num);
if (found)
cout << "\n\aError : Duplicate key " << endl;
else
insertNode (list, pPre, num);
}
infile.close();
return;
}
bool insertNode (LIST &list, NODE *&pPre, int num)
{
NODE *pNew;
if (! (pNew = new NODE))
return false;
pNew->data = num;
pNew->link = NULL;
if (pPre == NULL)
{
pNew->link = list.head;
list.head = pNew;
}
else
{
pNew->link = pPre->link;
pPre->link = pNew;
}
list.count++;
return true;
}
bool searchList(LIST list, NODE *&pPre, NODE *&pLoc, int target)
{
pPre = NULL;
pLoc = list.head;
while (pLoc && target > pLoc->data)
{
pPre = pLoc;
pLoc = pLoc->link;
}
return (pLoc ? target == pLoc->data : NULL);
}
bool getNext(LIST &list, int fromWhere, int &dataOut)
{
bool success;
if(fromWhere==0)
{
if(list.count==0)
success=false;
else
{
list.pos=list.head;
dataOut=list.pos->data;
success=true;
}
}
else
{
if(list.pos->link==NULL)
success=false;
else
{
list.pos=list.pos->link;
dataOut=list.pos->data;
success=true;
}
}
return success;
}
void printList (LIST list)
{
bool moreData; NODE *pos;
if(list.count==0)
cout<<"Sorry, nothing in the list"<<endl;
else
{
cout<<"Begin data Print: "<<endl;
list.count=0;
moreData=getNext(list,0,pos);
while(moreData=true)
{
list.count++;
cout <<setw(3)<<list.pos->data<<' ';
moreData=getNext(list,1,pos);
}
cout<<"count is "<<list.count<<endl;
cout <<endl;
}
}
void append (LIST &list1, LIST &list2)
{
NODE *pLoc;
if(list1.count==0)
list1.head=list2.head;
else
{
pLoc=list1.head;
if(pLoc->link!=NULL)
pLoc=pLoc->link;
pLoc->link=list2.head;
}
list1.count=list1.count+list2.count;
}