栈是一种先进后出的数据结构。
原c++栈的方法的基本用法:
- push(): 向栈内压入一个成员;
- pop(): 从栈顶弹出一个成员;
- empty(): 如果栈为空返回true,否则返回false;
- top(): 返回栈顶,但不删除成员;
- size(): 返回栈内元素的大小;
栈顶指针指向栈顶元素,出栈时先取栈顶元素,然后移动栈顶指针。
入栈时先移动栈顶指针,然后存入元素。
struct node{ char data; struct node *next; }; struct stack{ struct node *top; struct node *buttom; };
#创建栈 struct stack *create_stack(){ struct stack *sk=new stack; if(sk==NULL){ return false; } sk->buttom = NULL; sk->top=sk->buttom; return sk; }
#进栈 void push(struct stack *sk,char p){ node *n=new node; n->data=p; n->next=sk->top; sk->top=n; }
#出栈 void pop(struct stack *sk){ node *n=sk->top; sk->top=n->next; delete n; }
#栈是否空 bool isEmpty(struct stack *sk) { return(sk->top==sk->buttom); }
#获取栈顶元素 void top(struct stack *sk, char &c) { if(isEmpty(sk)) return; c = sk->data; }