您的位置:首页 > 理论基础 > 数据结构算法

数据结构 - C语言版 - 顺序栈 所有基本操作

2013-11-11 17:58 543 查看
C语言 - 顺序栈 所有基本操作


//结构体 定义为 数组 的方式
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 5

typedef struct Stack{
int data[MAXSIZE];
int top;
}Stack;

Stack *Init_SeqStack()
{
Stack *s;
s=malloc(sizeof(Stack));
s->top = -1;
return s;
}

void Push_Stack(Stack * S)
{
int i;

for(i=0; i<MAXSIZE; i++)
{
if(S->top== (MAXSIZE-1) )
{
printf("栈满,无法继续输入!\n");
break;
}

S->top++;

scanf("%d", &S->data[S->top] );
}
}

void Pop_Stack(Stack * S)
{

while(S->top != -1)
{
printf("%d ",S->data[S->top]);

S->top--;
}
}

int main(void)
{
Stack *S;

S = Init_SeqStack();

Push_Stack(S);
Pop_Stack(S);

printf("\n");
system("pause");
return 0;
}


//结构体 定义为 数组基地址 的方式
#include <stdio.h>
#define MAXSIZE 100
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
SqStack S;
int  InitStack(SqStack *S)
{
S->base= malloc(sizeof(SElemType[MAXSIZE]));
if(!S->base) return 0;
S->top = S->base;
S->stacksize=MAXSIZE;
return 1;
}

int Push(SqStack *S,SElemType e)
{
if((S->top)-(S->base) == S->stacksize)
return 0;
else
{
*S->top++=e;

return 1;
}
}
int Pop(SqStack *S,SElemType *e)
{
if(S->top==S->base) return 0;
else
{
*e = *--S->top;

return 1;
}
}

main()
{
int a;
InitStack(&S);
Push(&S,1);
Push(&S,2);
Push(&S,3);
Push(&S,4);
Push(&S,5);
Pop(&S,&a);
printf("%d\n",a);
Pop(&S,&a);
printf("%d\n",a);
Pop(&S,&a);
printf("%d\n",a);
Pop(&S,&a);
printf("%d\n",a);
Pop(&S,&a);
printf("%d\n",a);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息