数据结构-栈(C语言实现)
定义
一种先进后出的数据结构
实现
头文件:
#include<stdio.h>
#include<malloc.h>
typedef struct Node //定义节点
{
int data;
struct Node *pNext;
}*PNODE,NODE;
typedef struct Stack // 定义栈
{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
栈的初始化:
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if(pS->pTop == NULL)
{
printf("内存分配失败退出");
return;
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL;
}
}
判断栈非空
int isEmpty(PSTACK pS)
{
if(pS->pTop == pS->pBottom)
return 1;
else
return 0;
}
压栈
void push(PSTACK pS,int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
}
弹栈
int pop(PSTACK pS,int *val)
{
if(isEmpty(pS))
{
printf("空栈,出栈失败");
return 0;
}
else
{
PNODE p = pS->pTop;
pS->pTop = p->pNext;
if(val != NULL)
*val = p->data;
free(p);
return 1;
}
}
栈的遍历
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}
清空栈
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}
测试
int main()
{
STACK stack;
init(&stack);
push(&stack,10);
push(&stack,20);
push(&stack,30);
traverse(&stack);
int val;
int isPopSuccess = pop(&stack,&val);
if(isPopSuccess)
printf("pop的值为%d\n",val);
traverse(&stack);
clearStack(&stack);
traverse(&stack);
return 0;
}
应用:符号匹配