C语言中栈的表示和实现

2024-01-09 22:44
文章标签 语言 实现 表示 中栈

本文主要是介绍C语言中栈的表示和实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在 C 编程语言中,可以使用数组或链表实现堆栈。这两种实现都有其优点和注意事项,因此让我们探讨这两种方法。

1. 使用数组的堆栈实现:
   在此实现中,我们使用数组来表示堆栈。数组将具有固定大小,变量将跟踪堆栈的顶部元素。

''''c
   

#include <stdio.h>

#define MAX_SIZE 100

 

int stack[MAX_SIZE];

int top = -1;

 

// Function to check if the stack is empty

int isEmpty() {

    return (top == -1);

}

 

// Function to check if the stack is full

int isFull() {

    return (top == MAX_SIZE - 1);

}

 

// Function to push an element onto the stack

void push(int item) {

    if (isFull()) {

        printf("Stack Overflow\n");

        return;

    }

    stack[++top] = item;

}

 

// Function to pop an element from the stack

int pop() {

    if (isEmpty()) {

        printf("Stack Underflow\n");

        return -1; // Return an invalid value or handle error appropriately

    }

    return stack[top--];

}

 

// Function to get the top element of the stack

int peek() {

    if (isEmpty()) {

        printf("Stack is empty\n");

        return -1; // Return an invalid value or handle error appropriately

    }

    return stack[top];

}

 

// Function to display the elements of the stack

void display() {

    if (isEmpty()) {

        printf("Stack is empty\n");

        return;

    }

    printf("Stack elements: ");

    for (int i = top; i >= 0; i--) {

        printf("%d ", stack[i]);

    }

    printf("\n");

}

 

// Example usage

int main() {

    push(10);

    push(20);

    push(30);

    display(); // Output: Stack elements: 30 20 10

    printf("%d\n", pop()); // Output: 30

    printf("%d\n", peek()); // Output: 20

    display(); // Output: Stack elements: 20 10

    return 0;

}

```


   '''

2. 使用链表的堆栈实现:
   在此实现中,链表用于表示堆栈。链表的每个节点都包含数据和指向下一个节点的指针。

''''c

 

#include <stdio.h>

#include <stdlib.h>

 

struct Node {

    int data;

    struct Node* next;

};

 

struct Node* top = NULL;

 

// Function to check if the stack is empty

int isEmpty() {

    return (top == NULL);

}

 

// Function to push an element onto the stack

void push(int item) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    if (newNode == NULL) {

        printf("Memory allocation failed\n");

        return;

    }

    newNode->data = item;

    newNode->next = top;

    top = newNode;

}

 

// Function to pop an element from the stack

int pop() {

    if (isEmpty()) {

        printf("Stack Underflow\n");

        return -1; // Return an invalid value or handle error appropriately

    }

    struct Node* temp = top;

    int item = temp->data;

    top = top->next;

    free(temp);

    return item;

}

 

// Function to get the top element of the stack

int peek() {

    if (isEmpty()) {

        printf("Stack is empty\n");

        return -1; // Return an invalid value or handle error appropriately

    }

    return top->data;

}

 

// Function to display the elements of the stack

void display() {

    if (isEmpty()) {

        printf("Stack is empty\n");

        return;

    }

    printf("Stack elements: ");

    struct Node* current = top;

    while (current != NULL) {

        printf("%d ", current->data);

        current = current->next;

    }

    printf("\n");

}

 

// Example usage

int main() {

    push(10);

    push(20);

    push(30);

    display(); // Output: Stack elements: 30 20 10

    printf("%d\n", pop()); // Output: 30

    printf("%d\n", peek()); // Output: 20

    display(); // Output: Stack elements: 20 10

    return 0;

}

```


   '''

这两种实现都提供了堆栈的基本操作:“push”用于添加元素,“pop”用于删除顶部元素,“peek”用于检索顶部元素而不删除它,“display”用于打印堆栈的元素。

在基于数组的实现中,我们使用固定大小的数组,并使用“top”变量跟踪顶部元素。函数“isEmpty”和“isFull”分别检查堆栈是空的还是满的,以处理潜在的错误。“push”函数通过递增“top”并将值分配给数组中的相应索引来向堆栈添加元素。'pop' 函数通过递减 'top' 并从数组中返回值来删除 top 元素。“peek”函数在不修改堆栈的情况下返回顶部元素的值。“display”函数以相反的顺序遍历元素并打印它们。

在链表实现中,我们为链表的节点定义了一个结构,其中包含数据和指向下一个节点的指针。“top”指针指向堆栈中的第一个节点。“isEmpty”函数检查“top”指针是否为“NULL”,以确定堆栈是否为空。“push”函数创建一个新节点,分配数据并更新“next”指针以指向上一个顶部节点。“pop”函数删除顶部节点,更新“top”指针,并返回数据。“peek”函数返回顶部节点的数据,而不修改堆栈。“display”函数遍历链表并打印每个节点的数据。

请记住根据特定要求适当地处理错误情况,例如堆栈溢出或下溢。

 

这篇关于C语言中栈的表示和实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/588686

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

透彻!驯服大型语言模型(LLMs)的五种方法,及具体方法选择思路

引言 随着时间的发展,大型语言模型不再停留在演示阶段而是逐步面向生产系统的应用,随着人们期望的不断增加,目标也发生了巨大的变化。在短短的几个月的时间里,人们对大模型的认识已经从对其zero-shot能力感到惊讶,转变为考虑改进模型质量、提高模型可用性。 「大语言模型(LLMs)其实就是利用高容量的模型架构(例如Transformer)对海量的、多种多样的数据分布进行建模得到,它包含了大量的先验

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、