链栈基本操作
链栈储存结构
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
初始化
Status InitStack(LinkStack *S)
{
*S = NULL;
return OK;
}
入栈
Status push(LinkStack *S,ElemType e)
{
StackNode *p;
p = (StackNode *)malloc(sizeof(StackNode));
p->data = e;
p->next = *S;
*S = p;
return OK;
}
出栈
Status pop(LinkStack *S,ElemType *e)
{
if(*S == NULL) return ERROR;
StackNode *p;
*e = (*S)->data;
p = *S;
*S = (*S)->next;
free(p);
return OK;
}
判断是否为空
int isEmpty(LinkStack S)
{
if(S == NULL) return TRUE;
return FALSE;
}
一次入栈n个元素
void pushElems(LinkStack *S,int n)
{
int i;
ElemType e;
printf("请输入压栈的%d个元素:",n);
for(i=0;i<n;i++)
{
scanf("%d",&e);
push(S,e);
}
}
遍历
Status showElems(LinkStack S)
{
if(S == NULL) return ERROR;
StackNode *p = S;
printf("当前链栈:");
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
return OK;
}
清空链栈
Status clearStack(LinkStack *S)
{
if(*S == NULL) return ERROR;
ElemType e;
while(*S != NULL)
pop(S,&e);
free(&e);
return OK;
}
测试代码整合
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
Status InitStack(LinkStack *S)
{
*S = NULL;
return OK;
}
Status push(LinkStack *S,ElemType e)
{
StackNode *p;
p = (StackNode *)malloc(sizeof(StackNode));
p->data = e;
p->next = *S;
*S = p;
return OK;
}
Status pop(LinkStack *S,ElemType *e)
{
if(*S == NULL) return ERROR;
StackNode *p;
*e = (*S)->data;
p = *S;
*S = (*S)->next;
free(p);
return OK;
}
int isEmpty(LinkStack S)
{
if(S == NULL) return TRUE;
return FALSE;
}
void pushElems(LinkStack *S,int n)
{
int i;
ElemType e;
printf("请输入压栈的%d个元素:",n);
for(i=0;i<n;i++)
{
scanf("%d",&e);
push(S,e);
}
}
Status showElems(LinkStack S)
{
if(S == NULL) return ERROR;
StackNode *p = S;
printf("当前链栈:");
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
return OK;
}
Status clearStack(LinkStack *S)
{
if(*S == NULL) return ERROR;
ElemType e;
while(*S != NULL)
pop(S,&e);
free(&e);
return OK;
}
int main()
{
LinkStack S;
ElemType e;
printf("-------已初始化链栈---------\n");
InitStack(&S);
printf("\n-------链栈是否为空?-------\n");
printf("当前链栈情况:");
if(isEmpty(S)) printf("空栈\n");
else printf("非空栈\n");
printf("\n--------一次压栈n个元素--------\n");
pushElems(&S,5);
printf("\n-------链栈是否为空?-------\n");
printf("当前链栈情况:");
if(isEmpty(S)) printf("空栈\n");
else printf("非空栈\n");
printf("\n---------遍历栈内元素---------\n");
showElems(S);
printf("\n\n---------清空链栈-----------\n");
clearStack(&S);
printf("当前链栈情况:");
if(isEmpty(S)) printf("空栈\n");
else printf("非空栈\n");
printf("\n-----------100 压栈--------------\n");
push(&S,100);
printf("\n-----------出栈--------------\n");
pop(&S,&e);
printf("%d",e);
}