程序员

栈的链表表示

2018-06-13  本文已影响0人  星girl

初始化栈stack,用以存储全局变量top和bottom,ps为top和bottom的地址。

include <stdio.h>

include <stdlib.h>

include<stdbool.h>

//定义插入元素结构体类型
typedef struct node {
float m;
struct node Next;
}Node,
pnode;

//定义栈结构体类型
typedef struct Zhan {
Node * top;
Node * bottom;
}Stack,*pStack;

void Intial(pStack ps) {
ps->top = (Node *)malloc(sizeof(Node));
ps->bottom = ps->top;
if (ps->top == NULL) printf("栈的初始化error!");
else printf("栈的初始化success!");
}

void pushZhan(pStack ps,float datas) {
Node * new = (Node *)malloc(sizeof(Node));
new->m = datas;
new->Next = NULL;
new->Next = ps->top;
ps->top = new;
}

float popZhan(pStack ps) {
if (ps->top == ps->bottom) return -1;
float datas = ps->top->m;
Node *r = ps->top;
ps->top = ps->top->Next;
free(r);
return datas;
}

bool IsEmpt(pStack ps) {
bool r;
if (ps->top == ps->bottom)
{
r = true;
}
else { r = false; }
return r;
}

//展示栈中的元素
void ShowStack(pStack ps) {
Node * r = ps->top;
while (r != ps->bottom) {
printf("%f->", r->m);
r = r->Next;
}
}

void main() {
//初始化一个栈
pStack ps=(Stack *)malloc(sizeof(Stack));
Intial(ps);
//入队
pushZhan(ps, 3.8);
pushZhan(ps, 6.8);
pushZhan(ps, 8.8);
ShowStack(ps); printf("\n");
//出队
float a;
a = popZhan(ps);
printf("%f\n", a);
a = popZhan(ps);
printf("%f\n", a);
ShowStack(ps); printf("\n");
}
--------------------------------------实验结果展示----------------------------------------------

栈链表.png
上一篇 下一篇

猜你喜欢

热点阅读