堆栈的顺序存储
1.结构体定义2.入栈3.出栈4.初始化5.判断是否为空5.判断是否已满6.输出当前所有元素7.测试代码8.全部代码
1.结构体定义
顺序存储通常由一个一维数组和记录栈顶元素位置的变量构成。
#define MaxSize 100
typedef int ElementType
;
typedef struct SNode
*Stack
;
struct SNode
{
ElementType Data
[MaxSize
];
int Top
;
};
Stack PtrS
;
2.入栈
- 入栈返回void,出栈返回ElementType (当前元素)
void Push(Stack PtrS
,ElementType item
)
{
if(PtrS
->Top
==MaxSize
-1)
{
printf("堆栈满");
return ;
}
else
{
PtrS
->Data
[++(PtrS
->Top
)] = item
;
return;
}
}
3.出栈
ElementType
Pop(Stack PtrS
)
{
if(PtrS
->Top
== -1)
{
printf("堆栈空,不可出栈\n");
return ERROR
;
}
else
{
return PtrS
->Data
[(PtrS
->Top
)--] ;
}
}
4.初始化
Stack
CreateStack()
{
PtrS
= (Stack
)malloc(sizeof(struct SNode
));
PtrS
->Top
= -1;
return PtrS
;
}
5.判断是否为空
int IsEmpty(Stack PtrS
)
{
return (PtrS
->Top
==-1);
}
5.判断是否已满
int IsEmpty(Stack PtrS
)
{
return (PtrS
->Top
==-1);
}
6.输出当前所有元素
void print(Stack PtrS
)
{
if(IsEmpty(PtrS
))
{
printf("当前堆栈为空\n");
return;
}
printf("当前存储: ");
int temp
= PtrS
->Top
;
while(temp
!=-1)
{
printf("%d ",PtrS
->Data
[temp
]);
temp
--;
}
printf("\n");
}
7.测试代码
PtrS
= CreateStack();
printf("堆栈空? %d (1表示空,0表示满)\n",IsEmpty(PtrS
));
Pop(PtrS
);
printf("入栈:5\n");
Push(PtrS
,5);
print(PtrS
);
printf("入栈:3\n");
Push(PtrS
,3);
print(PtrS
);
printf("入栈:1\n");
Push(PtrS
,1);
print(PtrS
);
Push(PtrS
,1);
printf("堆栈满? %d (1表示满,0表示空)\n",IsFull(PtrS
));
printf("出栈:\n");
Pop(PtrS
);
print(PtrS
);
8.全部代码
#include<stdlib.h>
#include<stdio.h>
#define ERROR -1
#define MaxSize 3
typedef int ElementType
;
typedef struct SNode
*Stack
;
struct SNode
{
ElementType Data
[MaxSize
];
int Top
;
};
Stack PtrS
;
Stack
CreateStack()
{
PtrS
= (Stack
)malloc(sizeof(struct SNode
));
PtrS
->Top
= -1;
return PtrS
;
}
void Push(Stack PtrS
,ElementType item
)
{
if(PtrS
->Top
== MaxSize
-1)
{
printf("堆栈满");
return ;
}
else
{
PtrS
->Data
[++(PtrS
->Top
)] = item
;
return;
}
}
ElementType
Pop(Stack PtrS
)
{
if(PtrS
->Top
== -1)
{
printf("堆栈空,不可出栈\n");
return ERROR
;
}
else
{
return PtrS
->Data
[(PtrS
->Top
)--] ;
}
}
int IsFull(Stack PtrS
)
{
return (PtrS
->Top
==MaxSize
-1);
}
int IsEmpty(Stack PtrS
)
{
return (PtrS
->Top
==-1);
}
void print(Stack PtrS
)
{
if(IsEmpty(PtrS
))
{
printf("当前堆栈为空\n");
return;
}
printf("当前存储: ");
int temp
= PtrS
->Top
;
while(temp
!=-1)
{
printf("%d ",PtrS
->Data
[temp
]);
temp
--;
}
printf("\n");
}
int main()
{
PtrS
= CreateStack();
printf("堆栈空? %d (1表示空,0表示满)\n",IsEmpty(PtrS
));
Pop(PtrS
);
printf("入栈:5\n");
Push(PtrS
,5);
print(PtrS
);
printf("入栈:3\n");
Push(PtrS
,3);
print(PtrS
);
printf("入栈:1\n");
Push(PtrS
,1);
print(PtrS
);
Push(PtrS
,1);
printf("堆栈满? %d (1表示满,0表示空)\n",IsFull(PtrS
));
printf("出栈:\n");
Pop(PtrS
);
print(PtrS
);
system("pause");
return 0;
}