2012年(1008)
分类:
2012-08-01 11:19:09
原文地址:C_数据结构_栈 作者:luozhiyong131
/*顺序栈*/
#include
#define Maxsize 100 /*存储数据元素的最大个数*/
typedef int ElemType; /*存储数据元素的数据类型*/
typedef struct
{
ElemType data[Maxsize]; /*存储栈中元素*/
int top; /*栈顶指针*/
}Stack;
/**************************************************
函数名称:StackInit
入口参数:栈地址
出口参数:无
功能说明:初始化栈
***************************************************/
void StackInit(Stack *S) /*初始化栈*/
{
S->top = -1; /*空栈*/
}
/**************************************************
函数名称:Push
入口参数:栈地址,数据值
出口参数:0栈满,1成功
功能说明:压栈
***************************************************/
int Push(Stack *S,ElemType X) /*压栈*/
{
if(S->top == Maxsize - 1) /*栈是否已满*/
{
printf("Stack is full!\n");
return 0;
}
S->top++;
S->data[S->top] = X; /*压栈*/
return 1;
}
int IsEmpty(Stack *S) /*判栈空*/
{
if(S->top == -1)
return 0;
else
return 1;
}
ElemType Pop(Stack *S) /*出栈*/
{
ElemType temp;
if(IsEmpty(S) == 0)
{
printf("Stack is free!\n");
return 0;
}
temp = S->data[S->top]; /*数据弹出*/
S->top--;
return temp;
}
ElemType GetTop(Stack *S) /*取栈顶元素*/
{
ElemType temp;
if(IsEmpty(S) == 0)
{
printf("Stack is free!\n");
return 0;
}
temp = S->data[S->top]; /*数据弹出*/
return temp;
}
/******测试程序***********/
int main(void)
{
Stack top;
int i;
StackInit(&top);
for(i = 0; i < 10; i++)
Push(&top,i);
while(top.top != -1)
printf("%d ",Pop(&top));
printf("\n");
}
/*链栈*/
#include
#define ElemType int
typedef struct snode
{
ElemType data;
struct snode *next;
}LinkStack;
void StackInit(LinkStack **S) /*栈初始化*/
{
*S = (LinkStack *)malloc(sizeof(LinkStack));
(*S)->next = NULL;
}
int Push(LinkStack *S, ElemType X) /*压栈*/
{
LinkStack *p;
p = (LinkStack *)malloc(sizeof(LinkStack)); /*为节点分配一个内存空间*/
p->data = X;
p->next = S->next; /*新节点指针指向上次压入的元素地址*/
S->next = p; /*栈顶指向新节点*/
return 1;
}
int IsEmpty(LinkStack *S) /*判断栈空*/
{
return S->next == NULL?0:1;
}
ElemType Pop(LinkStack *S)
{
ElemType temp;
LinkStack *p;
if(IsEmpty(S) == 0)
{
printf("stack is free!\n");
return 0;
}
p = S->next;
temp = p->data; /*数据弹出*/
S->next = p->next; /*栈指针前移*/
free(p);
return temp;
}
ElemType GetTop(LinkStack *S) /*取栈顶元素*/
{
if(IsEmpty(S) == 0)
{
printf("stack is free!\n");
return 0;
}
return S->next->data;
}
/******测试程序******/
int main(void)
{
LinkStack *top;
int i;
StackInit(&top);
for(i = 0; i < 10; i++)
Push(top,i);
while(top->next != NULL)
printf("%d ",Pop(top));
printf("\n");
}