此代码在pop()
和serve()
上有无限循环。我不知道如何解决这个问题。
此代码在pop()
和serve()
上有无限循环。我不知道如何解决这个问题。
此代码在pop()
和serve()
上有无限循环。我不知道如何解决这个问题。
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <stack>
#include <queue>
#include "Queue.h"
#include "Stack.h"
using namespace std;
int main(){
Queue myqueue;
Stack mystack;
ifstream inputFile;
string fileName;
cout << "Enter the file name you would like to use with file type e.g. data.txt: ";
cin >> fileName;
inputFile.open(fileName);
string name;
int value;
cout << "Operation" << "\t" << "Stack" << "\t" << "Value" << "\t" << "Result" "\n";
cout << "------------------------------------------\n";
inputFile >> name >> value;
while (!inputFile.eof())
{
if (name == "push")
{
cout << name << "\t" << "\t" << "stack" << "\t" << value << "\t" << "success" << endl;
inputFile >> name >> value;
mystack.Push(value);
}
else if (name == "pop")
{
if (mystack.IsEmpty() == true)
{
cout << name << "\t" << "\t" << "stack" << "\t" << "---" << "\t" << "underflow" << endl;
}
else if (mystack.IsEmpty() == false)
{
cout << name << "\t" << "\t" << "stack" << "\t" << "---" << "\t" << "success" << endl;
}
inputFile >> name >> value;
mystack.Pop(value);
break;
}
else if (name == "append")
{
cout << name << "\t" << "\t" << "stack" << "\t" << value << "\t" << "success" << endl;
inputFile >> name >> value;
myqueue.append(value);
}
else if (name == "serve")
{
if (myqueue.IsEmpty() == true)
{
cout << name << "\t" << "\t" << "stack" << "\t" << "---" << "\t" << "underflow" << endl;
}
else if (myqueue.IsEmpty() == false)
{
cout << name << "\t" << "\t" << "stack" << "\t" << "---" << "\t" << "success" << endl;
}
inputFile >> name >> value;
myqueue.serve(value);
break;
}
}
cout << endl;
cout << "Stack" << endl;
cout << "-------" << endl;
mystack.Print();
cout << endl;
cout << "Queue" << endl;
cout << "-------" << endl;
myqueue.Print();
inputFile.close();
cout << endl;
system("Pause");
}
//-----------------------------------------------------------
// serve data from the queue.
//-----------------------------------------------------------
void Queue::serve(int &item)
{
// Check if empty
if (IsEmpty())
cout << "underflow\n";
// serve data
else
{
item = Data[Front];
Front = (Front + 1) % QUEUE_SIZE;
Count--;
}
}
//-----------------------------------------------------------
// Pop data from the stack.
//-----------------------------------------------------------
void Stack::Pop(int &Number)
{
// Check for empty stack
if (IsEmpty())
return;
// Extract information from node
Number = Head->Number;
// Pop item from linked list
SNode *Temp = Head;
Head = Head->Next;
delete Temp;
Length--;
// cout << "Pop " << Number << endl;
}
<Stack>
bool Stack::IsEmpty()
{
return (Length == 0);
}
<Queue>
bool Queue::IsEmpty()
{
return (Count <= 0);
}