1.栈的总结
出入栈的顺序:先入先出。两种情况:栈满,栈空。
操作:push,pop(弹出栈顶元素), peek (访问栈顶元素)
检测栈状态:stackEmpty(检测栈是否为空),stackFull(检测栈是否已满)
stack线性表实现
const int MaxStackSize=50;
class stack
{
private:
DataType Stacklist[MaxStackSize];
int top;
public:
//initilize
stack(void);
void push(const DataType item);
DataType pop();
void clearStack();
DataType seek() const;
int stackEmpty() const;
int stackFull() const;
}
//DataType is predefined with typedef;
stack::stack():top(-1);
stack::push(const DataType item)
{
if(top==Maxtacksize-1)
{
//the stack is full error
//error message;
exit(0);
}
top++;
Stacklist[top]=item;
}
DataType stack::pop()
{
if(top==-1)
{
//the stack is empty
//error message;
exit(0);
}
DateType temp=Stacklist[top];
top--;
return temp;
}
DataType stack:peek() const
{
if(top==-1)
{
//error message
exit(1);
}
return Sacklist[top];
}
int Stack:StackEmpty() const
{
return top==-1;
}
int Stack:StackFull() const
{
return top==MaxStackSize;
}
stack链表实现
typedef int elemType;
struct sNode{
elemType data;
struct sNode *next;
};
/* 1).初始化链栈为空 */
void initStack(struct sNode* *hs)//初始化
{
*hs = NULL;
return;
}
/* 2).向链中插入一个元素(入栈) */
void push(struct sNode* *hs, elemType x)
{
struct sNode *newP;
newP = malloc(sizeof(struct sNode));
if(newP == NULL){
printf("内在空间分配失败! ");
exit(1);
}
newP->data = x; /* 给新分配的结点赋值 */
/* 向栈顶插入新结点 */
newP->next = *hs;
*hs = newP;
return;
}
/* 3).从链栈中删除一个元素并返回它(出栈) */
elemType pop(struct sNode* *hs)
{
struct sNode *p;
elemType temp;
if(*hs == NULL){
printf("栈空无法删除! ");
exit(1);
}
/* 暂存栈顶结点指针,并使栈顶指针指向下一个结点 */
p = *hs;
*hs = p->next;
/* 暂存原栈顶元素以便返回,同时回收原栈顶结点 */
temp = p->data;
free(p);
return temp; /* 返回原栈顶元素 */
}
/* 4).读取栈顶元素 */
elemType peek(struct sNode* *hs)
{
/* 对于空栈则退出运行 */
if(*hs == NULL){
printf("栈空,无栈顶元素! ");
exit(1);
}
return (*hs)->data; /* 返回栈顶结点的值 */
}
/* 5).判断链栈是否为空,为空返回1,否则返回0 */
int emptyStack(struct sNode* *hs)
{
if(*hs == NULL){
return 1;
}else{
return 0;
}
}
/* 6).清除链栈为空 */
void clearStack(struct sNode* *hs)
{
struct sNode *cp, *np;
cp = *hs; /* 使cp指向栈顶结点 */
/* 从栈底依次删除每个结点 */
while(cp != NULL){
np = cp->next;
free(cp);
cp = np;
}
*hs = NULL; /* 置链栈为空 */
return;
}