用c語言實現stack的初始化,push,pop和Clear操做node
#include<stdio.h> #include<stdlib.h> #include<assert.h> struct Link { int data; struct Link* Next; }; struct Stack { struct Link* head; int Size; }; void StackInit(struct Stack* sta) { sta->head = NULL; sta->Size = 0; } void StackPush(struct Stack* sta, const int data) { struct Link* node; node = (struct Link*)malloc(sizeof(struct Link)); assert(node != NULL); node->data = data; node->Next = sta->head; sta->head = node; ++ sta->Size; } int StackEmpty(struct Stack* sta) { if(sta->Size == 0) return 1; return 0; } int StackPop(struct Stack* sta, int* data) { if(StackEmpty(sta)) return 0; struct Link* tmp = sta->head; *data = sta->head->data; sta->head = tmp->Next; free(tmp); -- sta->Size; return 1; } void StackClear(struct Stack* sta) { struct Link* tmp; while(sta->head) { tmp = sta->head; sta->head = tmp->Next; free(tmp); } sta->Size = 0; } int main() { struct Stack sta; StackInit(&sta); int i; for(i=1; i<=5; i++) StackPush(&sta, i); while(!StackEmpty(&sta)) { StackPop(&sta, &i); printf("%d\n", i); } return 0; }
C++實現ios
#include <iostream> using namespace std; class Stack { struct Link { int data; Link* Next; Link(int data_, Link* Next_):data(data_), Next(Next_) { } }; public: Stack():head(0),Size(0)///初始化,構造函數; { } ~Stack() { Link* tmp; while(head) { tmp = head; head = head->Next; delete tmp; } } void Push(const int data)///插入data; { Link* node = new Link(data, head); head = node; ++ Size; } bool Empty() { return (Size==0); } bool Pop(int& data) { if(Empty()) return false; Link* tmp = head; data = head->data; head = head->Next; delete tmp; Size--; return true; } private: Link* head; int Size; }; int main() { Stack sta; int i; for(i=1; i<=5; i++) { sta.Push(i); } while(!sta.Empty()) { sta.Pop(i); cout << i << endl; } return 0; }