链表实现动态栈

  链表实现动态栈
链表实现动态栈_第1张图片
程序实现

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

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 empty(PSTACK);
bool pop(PSTACK,int*);
void clear(PSTACK);

int main()
{
    int val = 0;
    STACK S;
    init(&S);
    push(&S,1);
    push(&S,2);
    push(&S,3);
    push(&S,4);
    traverse(&S);
    clear(&S);

    if(pop(&S,&val))
       printf("出栈成功,出栈值为%d\n",val);
    else
        printf("出栈失败\n");

    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;
    }
}

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 ",p->data);
        p=p->pNext;
    }
    printf("\n");
}

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

bool pop(PSTACK pS,int *pVal)
{
    if(empty(pS))
        return false;
    else
    {
        PNODE r = pS->pTop;
        pS->pTop = r->pNext;
        *pVal = r->data;
        free(r);
        r = NULL;

        return true;
    }
}

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


        PNODE p = pS->pTop;
        PNODE q = NULL;

        while(p != pS->pBottom)
        {
            q = p->pNext;
            free(p);
            p = q;
        }
        pS->pTop = pS->pBottom;

    }
}

你可能感兴趣的:(C基础,数据结构)