关闭

栈的操作(创建,入栈,出栈,清空,遍历等等)

标签: 遍历入栈出栈
1510人阅读 评论(0) 收藏 举报
分类:
#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 pS);
void push (PSTACK pS,int val);
void traverse(PSTACK pS);
bool pop(PSTACK pS,int * pVal);
bool empty(PSTACK pS);
void clear(PSTACK pS);


int main()
{
    STACK S;
int val;




init(&S);//造出一个空栈
for(int i=0;i<=15;i++)
{
      push(&S,i);
}
/*
push(&S,1);//压栈
push(&S,3);
push(&S,4);
push(&S,5);
push(&S,13);
push(&S,11);
*/
    traverse(&S);//遍历输出
//出栈
//pop(&S,&val);
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是%d\n",val);
}
else
{
     printf("出栈成功");
}
     traverse(&S);//遍历输出



//traverse(&S);//遍历输出


    clear(&S);//清空


    if(empty(&S))
{
printf("栈为空\n ");
}
else
{
          printf("栈为非空\n");
}


return 0;
}


void init(PSTACK pS)
{
pS->pTop=(PNODE)malloc(sizeof(NODE));
if(NULL==pS->pTop)
{
printf("动态内存分配失败");
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;
return;
}
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->pTop==pS->pBottom)
{
return true;
}
else
{
return false;
}
}
bool pop(PSTACK pS,int * pVal)
{
if(empty(pS))//pS存放的就是栈的地址
{
return true;
}
else
{
        PNODE r = pS->pTop;
* pVal = r->data;
pS->pTop = r->pNext;
free(r);
r = NULL;
return true;
}
}
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->pTop=pS->pBottom;
}
}
2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:187307次
    • 积分:3671
    • 等级:
    • 排名:第9187名
    • 原创:169篇
    • 转载:63篇
    • 译文:0篇
    • 评论:105条
    最新评论