1 #include<iostream> 2 #include<cstdlib> 3 4 struct node 5 { 6 7 int data; 8 node* next; 9 10 }; 11 12 class Stack 13 { 14 15 public: 16 17 node* head; 18 19 Stack(void); 20 ~Stack(); 21 22 void push(int x); 23 void pop(void); 24 25 int top(void); 26 int empty(void); 27 28 }; 29 30 Stack::~Stack() 31 { 32 33 head->next=NULL; 34 35 } 36 37 Stack::Stack(void) 38 { 39 40 Stack::head=(node*)malloc(sizeof(node)); 41 42 Stack::head->next=NULL; 43 44 } 45 46 void Stack::push(int x) 47 { 48 49 node* q=(node*)malloc(sizeof(node)); 50 51 q->data=x; 52 q->next=Stack::head; 53 54 Stack::head=q; 55 56 } 57 58 int Stack::empty(void) 59 { 60 61 if(Stack::head->next==NULL) return 1; 62 63 return 0; 64 65 } 66 67 void Stack::pop(void) 68 { 69 70 Stack::head=Stack::head->next; 71 72 } 73 74 int Stack::top(void) 75 { 76 77 return Stack::head->data; 78 79 } 80 81 int main() 82 { 83 84 int x; 85 Stack stk; 86 87 while(x){ 88 89 std::cin>>x; 90 91 stk.push(x); 92 93 } 94 95 while(!stk.empty()) 96 { 97 98 std::cout<<stk.top()<<" "; 99 100 stk.pop(); 101 102 } 103 104 105 106 return 0; 107 } 108 109
运行结果:
时间: 2024-10-09 01:26:29