本文共 1456 字,大约阅读时间需要 4 分钟。
要避免栈上溢,最好的办法就是使用链式存储结构,让多个栈共享所有可用的存储空间。所以,栈也可以采用链式存储结构表示,这种结构的栈简称为链栈。
新入栈的元素即为链表新的第一个结点,只要系统还有存储空间,就不会有栈满的情况发生。一个链栈可由一个栈顶指针top唯一确定。 采用带头结点的单链表实现栈。因为栈的插入和删除操作只在表头进行,所以链表的表头指针top就作为栈顶指针,top始终指向当前栈顶元素前面的头节点,即top->next为栈顶元素,当top->next==NULL,则代表栈空。 二、代码实现 stack.h#pragma once#includetypedef struct Stacknode { Elemtype data; struct Stacknode *next;}Stacktype;//初始化void InitStack(Stacktype **top) { *top = (Stacktype *)malloc(sizeof(Stacktype)); (*top)->next = NULL;}//入栈操作int pushStack(Stacktype *top, Elemtype x) { Stacktype *p; p = (Stacktype*)malloc(sizeof(Stacktype));//申请结点 p->data = x; p->next = top->next; top->next = p; return true;}//出栈操作Elemtype popStack(Stacktype *top) { Stacktype *p; Elemtype x; if (top->next == NULL) { printf("空栈!!"); return NULL; } else { p = top->next; top->next = p->next; x = p->data; free(p); return x; }}//取栈顶数据元素Elemtype GetTop(Stacktype *top) { if (top->next == NULL) { return NULL; } else { return (top->next->data); }}
源文件:
#include#include #include typedef int Elemtype;#include"stack.h"int main() { Stacktype *stack1; int x; InitStack(&stack1); printf("入栈的顺序为:"); for (int i = 0; i < 10; i++) { printf("%d ", i + 1); pushStack(stack1, i + 1); } printf("\n出栈的顺序为:"); while (stack1->next != NULL) { x = popStack(stack1); printf("%d ", x); } system("pause"); return 0;}
三、运行结果
转载地址:http://znzzi.baihongyu.com/