读书人

链栈的兑现

发布时间: 2012-11-10 10:48:50 作者: rapoo

链栈的实现

#include <iostream>using namespace std;#define ElemType inttypedef struct LNode{ElemType data;struct LNode *next;}Node;//链栈class ListStack{private:Node *head;int list_stack_size;Node * curr;public:ListStack(){list_stack_size = 0;head = curr = NULL;}bool push(ElemType e); //入栈void pop();bool isEmpty();ElemType Top();};bool ListStack::push(ElemType e){Node *current = (Node *)malloc(sizeof(Node));if(!current){cout<<"入栈失败\n";return false;}current->data = e;current->next = NULL;if(!head){head = current;curr = current;}else{curr->next = current;curr = current;}this->list_stack_size++;return true;}void ListStack::pop(){Node *prev, *current = head;if(!head->next){head = NULL;return;}while(current){if(current->next){prev = current;current = current->next;}elsebreak;}this->curr = prev;this->list_stack_size--;prev->next = NULL;}bool ListStack::isEmpty(){return head == NULL;}ElemType ListStack::Top(){Node *current = head;while(current->next){current = current->next;}return current->data;}int main(){ListStack stack;int e;cin>>e;while(e){stack.push(e % 2);e /= 2;}while(!stack.isEmpty()){cout<<stack.Top();stack.pop();}cout<<endl;return 0;}

读书人网 >编程

热点推荐