/*
单指针指向、无头结点的链栈
作者:S_hmily
日期:2011年8月31日
编译环境:VC++6.0
*/
/*********************************************************/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
/*********************************************************/
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
typedef struct node {
ElemType data;
struct node *next;
}StackNode, *pStackNode;
typedef struct {
pStackNode top;
int count;
}LinkStack;
/*********************************************************/
//初始化
Status InitLinkStack(LinkStack *S)
{
S->top = NULL;
S->count = 0;
return OK;
}
/*********************************************************/
//压栈
Status PushStack(LinkStack *S, ElemType e)
{
pStackNode pNew = (pStackNode)malloc(sizeof(StackNode));
pNew->data = e;
pNew->next = S->top;
S->top = pNew;
++S->count;
return OK;
}
/*********************************************************/
//出栈
Status PopStack(LinkStack *S, ElemType *e)
{
pStackNode p = S->top;
if (NULL == S->top)
return ERROR;
*e = p->data;
S->top = S->top->next;
free(p);
--S->count;
return OK;
}
/*********************************************************/
//打印栈中元素
void DispLinkStack(LinkStack *S)
{
pStackNode p = S->top;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
/*********************************************************/
int main(void)
{
LinkStack S;
ElemType e;
InitLinkStack(&S);
PushStack(&S, 1);
PushStack(&S, 2);
PushStack(&S, 3);
PushStack(&S, 4);
PushStack(&S, 5);
DispLinkStack(&S);
PopStack(&S, &e);
PopStack(&S, &e);
PopStack(&S, &e);
PopStack(&S, &e);
PopStack(&S, &e);
printf("\n\n%d ", e);
DispLinkStack(&S);
return 0;
}
链栈的实现(单指针 无头结点) C语言版
最新推荐文章于 2024-08-13 09:06:38 发布