注意理解下面的代码,数据的处理与转换。
头文件:
#ifndef STACK_H #define STACK_H class Stack { struct Link { void* data; Link* next; Link(void* dat, Link* nxt); ~Link(); }* head; public: Stack(); ~Stack(); void push(void *dat); void* peek(); void* pop(); }; #endif
实现文件:
#include "Stack.h" Stack::Link::Link(void* dat, Link* nxt) { data = dat; next = nxt; } Stack::Link::~Link(){} Stack::Stack() { head = 0; } void Stack::push(void *dat) { head = new Link(dat, head); } void* Stack::pop() { if (head == 0) return 0; void* result = head->data; Link* oldHead = head; head = head->next; delete oldHead; return result; } Stack::~Stack(){}
测试文件:
#include <iostream> #include "Stack.h" #include <cstdlib> #include <cassert> #include <string> #include <fstream> using namespace std; int main() { ifstream in("aa.txt"); Stack textlines; string line; while (getline(in, line)) textlines.push(new string(line)); string* s; while ((s = (string*)textlines.pop()) != 0) { cout << *s << endl; delete s; } system("pause"); }