您的位置:首页 > 编程语言 > C语言/C++

下推栈实现(c++编程思想 p136)

2015-06-08 15:20 513 查看
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 = 0;
}

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

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

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

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


3 测试文件main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "Stack.h"
#include "../require.h"

using namespace std;

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

requireArgs(argc, 1);

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

Stack textLines;
textLines.initialize();

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

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

textLines.cleanup();
return 0;
}


4 运行分析





附 辅助测试工具require.h

#ifndef REQUIRE_H
#define REQUIRE_H

#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>

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(1);
}
}

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

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

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(1);
}
}

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(1);
}
}

#endif // REQUIRE_H
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: