栈-基础代码积累

作者:Lew's Personal Blog 发布于:2019-12-17 14:36 Tuesday 分类:C/C++

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

typedef struct Node
{
int data;
struct Node * next;
}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 argc, char** argv)
{
STACK S;     //STACK等价于 struct Stack
int val;

init(&S);    //目的是建立一个空栈
push(&S, 1); //压栈
push(&S, 2);
push(&S, 3);
traverse(&S); //遍历输出
if (pop(&S, &val))
printf("出栈成功,出栈的元素为: %d \n", val);
else
printf("出栈失败!\n");
traverse(&S); //遍历输出
clear(&S);
traverse(&S); //遍历输出

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 = pS->pBottom
pS->pTop->next = NULL; //等价于pS->pBottom->next = NULL;
}
//return;
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));

pNew->data = val;
pNew->next = pS->pTop; //pS->pTop不能换成pS->pBottom
pS->pTop = pNew;
return;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop; //建一个遍历指针
while (p != pS->pBottom)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return;
}
bool empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
return true;
else
return false;
}
//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败返回false,否则返回true
bool pop(PSTACK pS, int *pVal)//传地址
{
if (empty(pS)) //pS本身存放的就是S的地址
{
return false; //栈空的时候出栈失败
}
else
{
PNODE r = pS->pTop; //创建一个指针用来指向出栈的元素
*pVal = r->data; //用pval存放出栈的元素
pS->pTop = r->next;
free(r);
r = NULL;
}
return true;
}
void clear(PSTACK pS)
{
PNODE p = pS->pTop;
PNODE q = NULL;
while (p != pS->pBottom)
{
q = p->next; //q用于存放p的后继,以防free(p)找不到p的后继
free(p);
p = q;
}
pS->pTop = pS->pBottom;
return;
}


标签:

发表评论 »本文目前尚无任何评论

发表评论

干净网络从你做起,切勿黏贴小广告