首页 > 代码库 > 数据结构之进栈出栈操作

数据结构之进栈出栈操作

先建立一个结构体节点:

typedef struct Node{

    int member;

 struct Node *pNext;

}Node,*pNode;

创建一个栈:

typedef struct stack{

 pNode Top;

 pNode Bot;

}Stack,*pStack;

 

//初始话栈内部

void Init_stack(pStack ps)

{

ps->Top= (pNode)malloc(sizeof(Node));

if (NULL == ps->Top)

exit(-1);

ps->Bot = ps->Top; 

ps->top->pNext = NULL;

}

 

 

//进栈操作

int Instack(pStack ps ,int data)

{

pNode pNew = (pNode)malloc (sizeof(Node));

pNew->member = data;

pNew->pNext = ps->Top;

ps->Top = pNew; //可以把它想象成一个书盒,然后你一本书一本书的朝里面放书

}

 

//出栈操作

//出栈操作需要释放空间

int Exit_Stack(pStack ps)

{

int m;

pNode pDel =(pNode)malloc(sizeof(Node));

pDel->member = ps->Top ->member ;

m = pDel->member

if (ps->Top == ps->Bot)

exit(-1);   

pDel = ps->Top ;

ps->Top = ps->Top->pNext;

free(pDel);

return m;

}

 

//栈的遍历

int Tracestack(pStack ps)

{

if (ps->Top == ps->Bot)

exit(-1);

while (NULL != ps->Top->Next )

{

printf(“ps->Top->member=%d",ps->Top->member);

ps->Top = ps->Top->pNext;

}

return 0;

}//也可以用栈底不等于栈顶的方式来循环

 

数据结构之进栈出栈操作