博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
栈的链式存储结构(带头结点的单链表实现)
阅读量:3948 次
发布时间:2019-05-24

本文共 1456 字,大约阅读时间需要 4 分钟。

一、 栈的链式存储结构(Visual studio开发环境)

     要避免栈上溢,最好的办法就是使用链式存储结构,让多个栈共享所有可用的存储空间。所以,栈也可以采用链式存储结构表示,这种结构的栈简称为链栈。

      新入栈的元素即为链表新的第一个结点,只要系统还有存储空间,就不会有栈满的情况发生。一个链栈可由一个栈顶指针top唯一确定。
     采用带头结点的单链表实现栈。因为栈的插入和删除操作只在表头进行,所以链表的表头指针top就作为栈顶指针,top始终指向当前栈顶元素前面的头节点,即top->next为栈顶元素,当top->next==NULL,则代表栈空。
在这里插入图片描述
二、代码实现
stack.h

#pragma once#include
typedef 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/

你可能感兴趣的文章
C语言数据类型笔记 by STP
查看>>
C语言指针笔记 by STP
查看>>
CoreLocation笔记 by STP
查看>>
Application Transport Security has blocked a cleartext HTTP (http://) 解决方案
查看>>
The identity used to sign the executable is no longer valid.解决方案
查看>>
Xcode增加pch文件
查看>>
CocoaPods安装和使用笔记 by STP
查看>>
Could not find developer disk image-解决方案
查看>>
升级Xcode之后VVDocumenter-Xcode不能用的解决办法
查看>>
iOS开发常见报错及解决方案 by STP
查看>>
SVN(Cornerstone)屏蔽/忽略不需要版本控制的UserInterfaceState.xcuserstate
查看>>
IOS 8 以上版本 设置applicationIconBadgeNumber和消息推送
查看>>
git常用命令
查看>>
Java 基本数据类型笔记by STP
查看>>
IDEA创建Maven项目时 loading archetype list转菊花转十年解决方案
查看>>
Mac启动tomcat
查看>>
报错: java.sql.SQLException: The server time zone value '�й�' is unrecognized or represents more ...
查看>>
使用xshell对服务器上的sql文件进行操作(mysql导入Linux)
查看>>
Spirngboot 后台操作一切正常并无报错,但是前端出现404错误
查看>>
java错误:java.lang.String can not be cast to java.math.BigDecimal
查看>>