栈是一种比较特殊的线性表。它最重要的特征就是遵循后进先出原则,而且它的进栈和出栈都在栈顶进行,所以它对元素进行插入和删除操作时相当于在线性表的一端进行。
对栈我们会有几步基本操作:
(1)首先要建立一个空栈,即初始化一个栈;
(2)向栈顶添加一个元素,即压栈;
(3)删除栈顶的元素,即弹栈;
(4)在压栈或弹栈的时候要检验栈是否已满或是否为空;
(5)还可以清空栈;
栈可以分为链式栈和顺序栈
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *pNext;
}Node, * NodePtr;
typedef struct stack
{
NodePtr pTop;
NodePtr pBottom;
}Stack, * StackPtr;
void init(StackPtr);
void push(StackPtr,int);
void printStack(StackPtr);
int pop(StackPtr,int *);
int empty(StackPtr);
void clear(StackPtr);
int main()
{
int val;
Stack S;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
printStack(&S);
//clear(&S);
if (pop(&S, &val)==1)
{
printf("出栈成功,出栈元素为%d\n", val);
}
else
{
printf("出栈失败\n");
}
printStack(&S);
return 0;
}
//初始化栈
void init(StackPtr pS)
{
pS->pTop = (NodePtr)malloc(sizeof(Node));
if (NULL == pS->pTop)
{
printf("动态内存分配失败\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL;
}
}
//压栈
void push(StackPtr pS, int val)
{
NodePtr pNew = (NodePtr)malloc(sizeof(Node));
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
}
void printStack(StackPtr pS)
{
NodePtr p = pS->pTop;
while (p != pS->pBottom)
{
printf("%d", p->data);
p = p->pNext;
}
printf("\n");
}
//检验栈是否为空
int empty(StackPtr pS)
{
if (pS->pTop == pS->pBottom)
{
return 1;
}
else
{
return 0;
}
}
//弹栈
int pop(StackPtr pS,int *pVal)
{
if (empty(pS) == 1)
{
return 0;
}
else
{
NodePtr r = pS->pTop;
*pVal = r->data;
pS->pTop = r->pNext;
free(r);
//r = NULL;
return 1;
}
}
//清空栈
void clear(StackPtr pS)
{
if (empty(pS)==1)
{
return;
}
else
{
NodePtr p = pS->pTop;
NodePtr q = NULL;
while (p != pS->pBottom)
{
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBottom;
}
}