下推栈实现(c++编程思想 p136)
阅读原文时间:2023年07月12日阅读:3

1 头文件Stack.h

#ifndef STACK_H
#define STACK_H

struct Stack
{

 struct Link  
 {  
     void\* data;  
     Link\* next;  
     void initialize(void\* dat, Link\* nxt);  
 }\* head;

 void initialize();  
 void push(void\* dat);  
 void\* peek();  
 void\* pop();  
 void cleanup();  

};

#endif // STACK_H

2 实现文件Stack.cpp

#include "Stack.h"
#include "../require.h"

using namespace std;

void Stack::Link::initialize(void* dat, Link* nxt)
{
data = dat;
next = nxt;
}

void Stack::initialize()
{
head = ;
}

void Stack::push(void* dat)
{
Link *newLink = new Link;
newLink->initialize(dat, head);
head = newLink;
}

void* Stack::peek()
{
require(head !=, "Stack empty");
return head->data;
}

void* Stack::pop()
{
if (head == )
return ;
void* result = head->data;
Link* oldHead = head;
head = head->next;
delete oldHead;
return result;
}

void Stack::cleanup()
{
require(head == , "Stack not empty");
}

3 测试文件main.cpp

#include
#include
#include
#include "Stack.h"
#include "../require.h"

using namespace std;

int main(int argc, char* argv[])
{

 requireArgs(argc, );

 ifstream in(argv\[\]);  
 assure(in, argv\[\]);

 Stack textLines;  
 textLines.initialize();

 string line;  
 while (getline(in, line)) //文件以行为单位入栈  
     textLines.push(new string(line));

 string\* s;  
 while ((s = (string\*) textLines.pop()) != ) //出栈  
 {  
     cout << \*s << endl;  
     delete s;  
 }

 textLines.cleanup();  
 return ;  

}

4 运行分析

附 辅助测试工具require.h

#ifndef REQUIRE_H
#define REQUIRE_H

#include
#include
#include
#include

inline void require(bool requirement, const std::string& msg = "Requirement failed")
{
using namespace std;
if (!requirement)
{
fputs(msg.c_str(), stderr);
fputs("\n", stderr);
exit();
}
}

inline void requireArgs(int argc, int args, const std::string& msg = "Must use %d arguments")
{
using namespace std;
if (argc != args + )
{
fprintf(stderr, msg.c_str(), args);
fputs("\n", stderr);
exit();
}
}

inline void requireMinArgs(int argc, int minArgs, const std::string& msg ="Must use at least %d arguments")
{
using namespace std;
if(argc < minArgs + )
{
fprintf(stderr, msg.c_str(), minArgs);
fputs("\n", stderr);
exit();
}
}

inline void assure(std::ifstream& in, const std::string& filename = "")
{
using namespace std;
if(!in)
{
fprintf(stderr, "Could not open file %s\n",
filename.c_str());
exit();
}
}

inline void assure(std::ofstream& out, const std::string& filename = "")
{
using namespace std;
if(!out) {
fprintf(stderr, "Could not open file %s\n",
filename.c_str());
exit();
}
}

#endif // REQUIRE_H