动态栈是用链表实现的,优点是栈的内存充足。
结构代码
/节点
typedef struct Node{
int data;
struct Node *pNext;
}NODE,*PNODE;
//栈
typedef struct Stack{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
1、初始化
void init(PSTACK pStack){
//分配内存
pStack->pTop=(PNODE)malloc(sizeof(NODE));
if(NULL==pStack->pTop){
printf("动态分配内存失败");
exit(-1);
}else{
//初始化,没有数据在栈中时,栈顶和栈底都指向同一方向
//然后是栈底中的指针域设置为空
pStack->pBottom=pStack->pTop;
pStack->pBottom->pNext=NULL;
}
}
2、压栈
void push(PSTACK pStack,int val)
{
//分配新节点
PNODE pNew=(PNODE)malloc(sizeof(NODE));
//为新的节点赋值
pNew->data=val;
//将新节点的指针域指向栈顶
pNew->pNext=pStack->pTop;
//将栈顶指向pNew
pStack->pTop=pNew;
return;
}
3、出栈
bool pop(PSTACK pStack,int *pVal){
//判断栈是否为空
if(is_empty(pStack)){
return false;
}else{
//分配临时的 PNODE,用来保存栈顶
PNODE temp=pStack->pTop;
//将出栈的元素保存起来
*pVal=temp->data;
//将栈顶指向下一个 PNODE
pStack->pTop=temp->pNext;
//释放临时
free(temp);
temp=NULL;
return true;
}
}
4、判断是否为空
bool is_empty(PSTACK pStack){
if(pStack->pTop==pStack->pBottom)
return true;
else
return false;
}
5、遍历
void traverse(PSTACK pStack){
//定义一个临时PNODE,不改变栈顶和栈底
if(is_empty(pStack)){
printf("栈没有元素!");
}
PNODE p=pStack->pTop;
while(p!=pStack->pBottom){
printf("%d ",p->data);
p=p->pNext;
}
printf("\n");
}
6、清空里面的数据
void clear(PSTACK pStack){
//判断栈是否为空
if(is_empty(pStack))
return;
else{
//先从栈顶
PNODE p=pStack->pTop;
PNODE q=NULL;
//p q上下交替相互赋值
while(p!=pStack->pBottom){
q=p->pNext;
free(p);
p=q;
}
//使栈顶等于栈底
pStack->pTop=pStack->pBottom;
}
}
测试代码
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//方法声明
void init(PSTACK pStack);
void push(PSTACK pStack,int val);
void traverse(PSTACK pStack);
bool pop(PSTACK pStack,int *pVal);
bool is_empty(PSTACK pStack);
void clear(PSTACK pStack);
int main()
{
STACK s;//STACK等价于struct Stack;
int pVal;
//初始化
init(&s);
//入栈
push(&s,2);
push(&s,1);
push(&s,3);
push(&s,1);
push(&s,5);
push(&s,1);
//遍历
traverse(&s);
pop(&s,&pVal);
traverse(&s);
printf("出栈的元素是pVal=%d\n",pVal);
clear(&s);
traverse(&s);
}
代码下载:http://download.csdn.net/detail/a_person_alone/9488628