class stack { struct link { void* data; link* next; void initialize(void* Data,link* Next); }* head; public: stack(); ~stack(); void push(void* Data); void* peek(); void* pop(); }; #include<stdlib.h> #include<assert.h> #include<stdio.h> #include<string.h> void stack::link::initialize(void* Data,link* Next) { data=Data; Next=next; } stack::stack() {head=0;} void stack::push(void* Data) { link* newlink=(link*)malloc(sizeof(link)); assert(newlink); newlink->initialize(Data,head); head=newlink; } void stack::peek() {return head->data;} void stack::pop() { if(head==0) return 0; void* result=head->data; link* oldHead=head; head=head->next; free(oldHead); return result; } stack::~stack() { link* cursor=head; while(head) { cursor=cursor->next; free(head->data); free(head); head=cursor; } }
main(int argc,char** argv) { assert(argc==2); FILE* file=fopen(argv[1],"r"); assert(file); #define BUFSIZE 100 char buf[BUFSIZE]; stack textlines; while(fgets(buf,BUFSIZE,file)) { char* string=(char*)malloc(strlen(buf)+1); assert(string); strcpy(string,buf); textlines.push(string); } char* s; while((s=(char*)textlines.pop())!=0) { printf("%s",s);free(s); } } //老是编译有问题,请大家帮忙看看