首页 > 代码库 > 栈—代码

栈—代码

#include <stdio.h>#include <malloc.h>#include <stdlib.h>//局部变量在栈里面分配。静态分配都在栈里面分配,动态都在堆里面分派的。typedef struct Node{    int data;    struct Node *pNext;}NODE, * PNODE;                //NODE等价于struct Node。PNODE等价于struct Node*typedef struct Stack{    PNODE pTop;    PNODE pButtom;}STACK, * PSTACK;//void init(PSTACK);void push(PSTACK, int);void traverse(PSTACK);bool pop(PSTACK, int *);void clear(PSTACK);int main(void){    int val;    STACK S;    init(&S);    push(&S, 1);    push(&S, 2);    push(&S, 3);    push(&S, 4);    push(&S, 5);    push(&S, 6);    push(&S, 7);    push(&S, 8);    traverse(&S);    clear(&S);    traverse(&S);    if(pop(&S, &val))    {        printf("出栈成功,出栈的元素是%d\n",val);    }    else    {        printf("出栈失败");    }    return 0;}void init(PSTACK pS){    pS->pTop = (PNODE)malloc(sizeof(NODE));    if (NULL == pS->pTop)    {        printf("动态分配失败!\n");        exit(-1);    }    else    {        pS->pButtom = pS->pTop;        pS->pButtom->pNext = NULL;//pS->pTop->pNext = NULL;    }}void push(PSTACK pS, int val){    PNODE pNew = (PNODE)malloc(sizeof(NODE));    pNew->data =http://www.mamicode.com/ val;    pNew->pNext = pS->pTop;    pS->pTop = pNew;    return;}void traverse(PSTACK pS){    PNODE p = pS->pTop;     while(p != pS->pButtom)    {        printf("%d", p->data);        p = p->pNext;    }    printf("\n");    return;}bool empty(PSTACK pS){    if(pS->pButtom ==pS->pTop)        return true;    else        return false;}//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中。如果出栈失败返回false。bool pop(PSTACK pS, int *pVal){    if(empty(pS))   //pS本身存放的就是S的地址    {        return false;    }    else    {        PNODE q = pS->pTop;            *pVal = q->data;        pS->pTop = q->pNext;        free(q);        q = NULL;        return true;    }}//清空数据void clear(PSTACK pS){    if(empty(pS))    {        return;    }    else    {        PNODE p = pS->pTop;        PNODE q =NULL;        while(p !=pS->pButtom)        {            q = p->pNext;            free(p);            p = q;        }        pS->pTop = pS->pButtom;    }}

 

栈—代码