#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}Node ,*PNode;
typedef struct stack {
PNode pTop;
PNode pBot;
}Stack, *PStack;
void init(PStack pS)
{
pS->pTop = pS->pBot = (PNode)malloc(sizeof(Node));
pS->pBot->next = NULL;
}
void push(PStack pS, int val)
{
PNode pNew = (PNode)malloc(sizeof(Node));
pNew->data = val;
pNew->next = pS->pTop;
pS->pTop = pNew;
}
void traverse(PStack pS)
{
PNode p = pS->pTop;
while (p != pS->pBot) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void pop(PStack pS)
{
if (pS->pTop != NULL) {
if (pS->pTop == pS->pBot) {
printf("已到栈底\n");
return;
}
PNode p = pS->pTop;
pS->pTop = p->next;
free(p);
p = NULL;
}
}
void clean(PStack pS)
{
PNode q = NULL;
while (pS->pTop != pS->pBot){
q = pS->pTop->next;
free(pS->pTop);
pS->pTop = q;
}
}
int main(void)
{
Stack s;
init(&s);
push(&s, 5);
push(&s, 4);
push(&s, 3);
push(&s, 2);
push(&s, 1);
traverse(&s);
pop(&s);
traverse(&s);
clean(&s);
pop(&s);
traverse(&s);
system("pause");
return 0;
}
栈的出栈、入栈、遍历、清空操作
最新推荐文章于 2024-07-23 16:53:03 发布