马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 ~风介~ 于 2014-5-15 23:59 编辑
1.顺序栈#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
char stackSize;
} sqStack;
void InitStack(sqStack *s)
{
s->base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!s->base)
{
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void ClearStack(sqStack *s)
{
s->base = s->top;
}
void DestroyStack(sqStack *s)
{
int i,len;
len = s->stackSize;
for(i=0;i<len;i++)
{
free(s->base);
s->base++;
}
s->base = s->top = NULL;
s->stackSize = 0;
}
void Push(sqStack *s,ElemType e)
{
if(s->top - s->base >= s->stackSize)
{
s->base = (ElemType *)realloc(s->base,(s->stackSize + STACKINCREMENT)*sizeof(ElemType));
if(!s->base)
{
exit(0);
}
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack *s,ElemType *e)
{
if(s->top == s->base)
{
return;
}
*e = *--(s->top);//先将top指针--再把内容赋值
}
int StackLen(sqStack s)
{
return (s.top-s.base);
}
void GetTop(sqStack *s,ElemType *j)
{
if(s->top!=NULL)
{
*j = *--(s->top);
s->top++;
}
else
{
printf("栈空!");
}
}
int main()
{
ElemType c,j;
sqStack s;
int len,i;
InitStack(&s);
printf("请输入整数<#结束>:");
scanf("%c",&c);
while(c != '#')
{
Push(&s,c);
scanf("%c",&c);
}
getchar();
len = StackLen(s);
printf("栈的当前容量是: %d\n", len);
GetTop(&s,&j);
printf("栈顶是:%c\n",j);
printf("出栈的结果是:");
for(i=0;i<len;i++)
{
Pop(&s,&c);
printf("%c",c);
}
return 0;
}
2.链栈#include<stdio.h>
#include<stdlib.h>
#define SACK_INIT_SIZE 20
#define INCREMENT 10
typedef char ElemType;
typedef int Status;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode;
typedef struct LinkStack
{
StackNode *top;
int count;
}LinkStack;
Status InitStack(LinkStack *s)
{
s->top=(StackNode *)malloc(sizeof(StackNode));
if(s->top==NULL)
printf("分配空间失败!");
s->top=NULL;
s->count = 0;
return 0;
}
Status StackEmpty(LinkStack s)
{
if(s.count==0)
return 1;
else
return 0;
}
Status Push (LinkStack *s,ElemType e)
{
StackNode *p = (StackNode*)malloc(sizeof(StackNode));
p->data =e;
p->next = s->top;
s->top = p;
s->count++;
return 0;
}
Status Pop(LinkStack *s,ElemType *e)
{
StackNode *p;
if(StackEmpty(*s))
{
printf("栈空");
exit(0);
}
*e = s->top->data;
p=s->top;
s->top=s->top->next;
free(p);
s->count--;
return 0;
}
Status GetTop(LinkStack *s,ElemType *e)
{
if(s->top!=NULL)
*e=s->top->data;
else
printf("栈空!");
return 0;
}
Status StackLen(LinkStack s)
{
return (s.count);
}
int main()
{
ElemType c,j,d;
LinkStack s;
int len,i;
InitStack(&s);
printf("请输入整数<#结束>:");
scanf("%c",&c);
while(c != '#')
{
Push(&s,c);
scanf("%c",&c);
}
getchar();
len=StackLen(s);
printf("栈的当前容量是: %d\n", len);
GetTop(&s,&j);
printf("栈顶是:%c\n",j);
printf("出栈的结果是:");
for(i=0;i<len;i++)
{
Pop(&s,&d);
printf("%c",d);
}
return 0;
}
截图:
后继操作会继续补充~ ^_^
|