栈 操作(用例)(C语言)

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

typedef struct Node
{
    int data;
    struct Node * pNext;
}NODE,* PNODE;

typedef struct Stack
{
    PNODE pTop;
    PNODE pBottom;
}STACK,* PSTACK;


void init(PSTACK);
void pop(PSTACK ps, int *pval);
bool empty(PSTACK ps);
void traverse(PSTACK ps);
void clear(PSTACK ps);
void push(PSTACK ps,int val);

int main()
{
STACK s;
int val;
init(&s);
push(&s,1);
push(&s,2);
push(&s,3);
push(&s,4);
push(&s,5);
push(&s,6);
traverse(&s);
pop(&s,&val);
printf("出栈的元素值是: %d\n",val);
traverse(&s);
clear(&s);
traverse(&s);
return 0;
}

void init(PSTACK ps)
{
    ps->pTop = (PNODE)malloc(sizeof(NODE));
    if(NULL == ps->pTop)
    {
        printf("动态内存分配失败!\n");
        exit(-1);
    }
    else
    {
        ps->pBottom = ps->pTop;
        ps->pTop->pNext = NULL;
    }
}

bool empty(PSTACK ps)
{
    if(ps->pTop == ps->pBottom)
        return true;
    else
    return false;
}

void push(PSTACK ps,int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = ps->pTop;
ps->pTop = pNew;
}

void pop(PSTACK ps, int *pval)
{
if(empty(ps))
{
return ;
}
else
{
PNODE r = ps->pTop;
*pval = r->data;
ps->pTop = r->pNext;
free(r);
r = NULL;
return;
}
}

void traverse(PSTACK ps)
{
PNODE p = ps->pTop;
while(p != ps->pBottom)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
return;
}

void clear(PSTACK ps)
{
if(empty(ps))
{
return;
}
else
{
PNODE p = ps->pTop;
PNODE q = NULL;
while(p != ps->pBottom)
{
q = p->pNext;
free(p);
p = q;
}
ps->pBottom = ps->pTop;
}
}


分享到:

发表评论

昵称

沙发空缺中,还不快抢~