Here is the solution, I have tried compiled it and run it with both
MSVC, and g++/Linux. It worked fine for me both times:
#include <string.h>
#include <stdio.h>
#define MAX_NAMES 11
#define MAX_NAME_LEN 255
class cQueue
{
private:
char szNameList[MAX_NAMES][MAX_NAME_LEN];
int nListLen;
public:
cQueue() { nListLen = 0;}
bool add(char* szName);
bool remove();
void display();
};
class cPriorityQueue
{
private:
char szNameList[MAX_NAMES][MAX_NAME_LEN];
int nPriorityList[MAX_NAMES];
int nListLen;
void insert(char* szName, int nPriority, int nIndex);
public:
cPriorityQueue()
{
nListLen = 0;
memset(szNameList, 0, MAX_NAMES * MAX_NAME_LEN *
sizeof(char));
memset(nPriorityList, 0, MAX_NAMES * sizeof(int));
}
bool add(char* szName, int nPriority);
bool remove();
void display();
};
bool cQueue::add(char* szName)
{
if (nListLen < MAX_NAMES-1)
{
strcpy(szNameList[nListLen++], szName);
}
else
{
fprintf(stderr, "Error: Queue full\n");
return false;
}
return true;
}
bool cQueue::remove()
{
int i;
if (nListLen > 0) {
for (i = 0; i < nListLen; i++)
{
strcpy(szNameList[i], szNameList[i+1]);
}
nListLen--;
}
else
{
fprintf(stderr, "Error: Queue empty\n");
return false;
}
return true;
}
void cQueue::display()
{
int i;
for (i = 0; i < nListLen; i++)
{
printf("%s\n", szNameList[i]);
}
}
bool cPriorityQueue::add(char* szName, int nPriority)
{
int i;
if ((nPriority > 10) || (nPriority < 1))
{
fprintf(stderr, "Error: Invalid priority\n");
return false;
}
else if (nListLen < MAX_NAMES-1)
{
nListLen++;
for (i = nListLen-1; i >= 0; i--)
{
if ((i == 0) || (nPriorityList[i - 1] <= nPriority)) {
insert(szName, nPriority, i);
break;
}
}
}
else
{
fprintf(stderr, "Error: Queue full\n");
return false;
}
return true;
}
bool cPriorityQueue::remove()
{
int i;
if (nListLen > 0) {
for (i = 0; i < nListLen; i++)
{
strcpy(szNameList[i], szNameList[i+1]);
}
nListLen--;
}
else
{
fprintf(stderr, "Error: Queue empty\n");
return false;
}
return true;
}
void cPriorityQueue::display()
{
int i;
for (i = 0; i < nListLen; i++)
{
printf("%s: %i\n", szNameList[i], nPriorityList[i]);
}
}
void cPriorityQueue::insert(char* szName, int nPriority, int nIndex)
{
int i;
for (i = nListLen; i > nIndex; i--)
{
strcpy(szNameList[i], szNameList[i-1]);
nPriorityList[i] = nPriorityList[i-1];
}
strcpy(szNameList[nIndex], szName);
nPriorityList[nIndex] = nPriority;
}
int main() {
cQueue Queue;
cPriorityQueue PriorityQueue;
int i, nPriority;
char szName[MAX_NAME_LEN];
for (i = 0; i < MAX_NAMES-1; i++)
{
printf("Please enter a name: ");
fscanf(stdin, "%s", szName);
printf("Please enter a priority: ");
fscanf(stdin, "%i", &nPriority);
if (PriorityQueue.add(szName, nPriority))
{
Queue.add(szName);
}
else
{
i--;
}
}
printf("\n\nRegular queue:\n");
Queue.display();
printf("\n\nPriority queue:\n");
PriorityQueue.display();
return 0;
}
Please let me know if you have any questions, or comments. I will be
more than happy to assist further.
Thanks,
--jld |