#include
#include
#include
#include
typedef struct Node
{
int data;
struct Node * pNext;
}NODE, * PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK, * PSTACK; //PSTACK等價于struct STACK *
void init(PSTACK); //初始化棧
void push(PSTACK, int ); //壓棧
void traverse(PSTACK); //遍歷
bool pop(PSTACK pS,int * pVal); //出棧
void clear(PSTACK pS); //清空棧
int main(void)
{
STACK S; //STACK等價于struct Stack
int val;
init(&S); //造出空棧
push(&S, 1); //壓棧
push(&S, 2);
push(&S, 3);
push(&S, 4);
push(&S, 5);
push(&S, 6);
traverse(&S); //遍歷輸出
/*
if(pop(&S,&val))
{
printf("出棧成功,出棧的元素是%d\n", val);
}
else
{
printf("出棧失敗!\n");
}
*/
clear(&S);
traverse(&S);
return 0;
}
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if(NULL == pS->pTop)
{
printf("動態(tài)內(nèi)存分配失敗\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL;
}
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE)); //創(chuàng)建新的節(jié)點
pNew->data = val; //將val的值賦給新節(jié)點的數(shù)據(jù)域
pNew->pNext = pS->pTop; //將新節(jié)點的指針域指向下一個節(jié)點.pS->Top不能改寫成pS->Bottom
pS->pTop = pNew; //pTop指向新節(jié)點
return;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
bool empty(PSTACK pS)
{
if(pS->pTop == pS->pBottom)
{
return true;
}
else
{
return false;
}
}
bool pop(PSTACK pS,int * pVal)
{
if(empty(pS))
{
return false;
}
else
{
PNODE r = pS->pTop;
*pVal = r->data;
pS->pTop = r->pNext;
free(r);
r = NULL;
return true;
}
}
//清空棧
void clear(PSTACK pS)
{
if(empty(pS)) //如果
{
return;
}
else
{
PNODE p = pS->pTop; //定義元素p指向棧頂元素
PNODE q = NULL; //定義元素q,初始值為空
while(p !=pS->pBottom) //如果棧不為空
{
q = p->pNext; //q指向p的下一個元素
free(p); //釋放p所指向的棧頂元素
p = q; //將q所指向的元素賦給p
}
pS->pTop = pS->pBottom;
}
}
當(dāng)前文章:C語言實現(xiàn)棧的基本操作
分享鏈接:
http://weahome.cn/article/jpsehg.html