码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构(栈的实现与遍历)C语言实现

时间:2018-06-18 16:04:41      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:struct   span   clu   结构   exit   tst   数据   stack   AC   

# 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 pBottm;
}STACK,* PSTACK;

void initStack(PSTACK pS);
void pushStack(PSTACK pS,int val);
void traverseStack(PSTACK pS);

int main(void)
{
    STACK s;

    initStack(&s);
    pushStack(&s,1);
    pushStack(&s,2);
    pushStack(&s,3);
    pushStack(&s,4);
    pushStack(&s,5);
    traverseStack(&s);

    return 0;
}
void initStack(PSTACK pS)
{
    pS->pTop=(PNODE)malloc(sizeof(NODE));
    if(pS->pTop==NULL)
    {
        printf("动态内存分配失败!\n");
        exit(-1);
    }
    else
    {
        pS->pBottm=pS->pTop;//pS->pBottm->pNext=pS->pTop->pNext ?
        pS->pTop->pNext=NULL;
    }
}
void pushStack(PSTACK pS,int val)
{
    PNODE pNew=(PNODE)malloc(sizeof(NODE));
    pNew->data=val;
    pNew->pNext=pS->pTop;//因为刚开始pTop和pBottom指向的都是同一个节点,所以pS->pTop=pS->pBottom
    pS->pTop=pNew;
    
    return;
}
void traverseStack(PSTACK pS)
{
    PNODE p=pS->pTop;
    while(p !=pS->pBottm)
    {
        printf("%d ",p->data);
        p=p->pNext;
    }
    printf("\n");
    return;
}

 

数据结构(栈的实现与遍历)C语言实现

标签:struct   span   clu   结构   exit   tst   数据   stack   AC   

原文地址:https://www.cnblogs.com/zhujialei123/p/9195227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!