数据结构伪代码的实现(栈)

数据结构伪代码的实现(栈)

#include 
#include 
#include 
#include 

typedef struct Node
{
    int data;
    struct Node *pNext;
}NODE,*pNODE;//定义栈的每一个元素类型和指针

typedef struct Stack
{
    pNODE pTop;//栈顶
    pNODE pBottom;//栈底
}STACK,*pSTACK;//定义一个栈和栈的指针  栈顶和栈底指向结点

void init(pSTACK );
void push(pSTACK ,int );
void traverse(pSTACK );
bool pop(pSTACK ,int *);
void clear(pSTACK );
bool is_empty(pSTACK );

int main(void)
{
    STACK s;//定义一个栈
    int val;

    init(&s);//初始化
    //入栈操作
    push(&s,1);
    push(&s,33);
    push(&s,9);
    push(&s,7);
    push(&s,8);
    //遍历
    traverse(&s);
    //出栈操作
    if(pop(&s,&val))
    {
        printf("出栈成功!出栈的数字是:%d\n",val);
    }else printf("出栈失败!");
    traverse(&s);
    //清空
    clear(&s);
    if(is_empty(&s))
        printf("栈为空!\n");

    return 0;
}

void init(pSTACK ps)
{
    ps->pTop=(pNODE)malloc(sizeof(NODE));
    if(ps->pTop==NULL)
    {
        printf("内存分配失败!\n");
        exit(-1);
    }
    else  
    {
        //初始化
        ps->pBottom=ps->pTop;
        ps->pTop->pNext=NULL;
    }
}

void push(pSTACK ps,int val)
{
    pNODE pNew=(pNODE)malloc(sizeof(NODE));//创建新节点
    pNew->data=val;
    pNew->pNext=ps->pTop;//新节点的指针指向上一个元素
    ps->pTop=pNew;//栈顶指向新节点
}

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

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

//出栈一次
bool pop(pSTACK ps,int *pval)
{
    if(is_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(is_empty(ps))
        return ;
    else
    {
        pNODE p=ps->pTop;
        pNODE q=NULL;

        while(p!=ps->pBottom)
        {
            //让q指向p的上一个元素,然后free p,把q赋值给p  循环
            q=p->pNext;
            free(p);
            p=q;
        }
        ps->pTop=ps->pBottom;
    }
    
}

你可能感兴趣的:(栈,链表,经验分享)