数据结构示例之用链表实现栈
来源:互联网 发布:淘宝香水嗅觉系真假 编辑:程序博客网 时间:2024/06/01 08:59
以下是“使用链表实现栈”的简单示例:
1. 用c语言实现的版本
#include<stdio.h>#include<stdlib.h>struct s_node{int data;struct s_node *next;};typedef struct s_node* pNode;pNode stack = NULL;int pCount = 0;/* 打印栈的内容 */void print_stack(){pNode temp = NULL;temp = stack;if (temp == NULL){printf("The stack is empty!\n");}else{while (temp != NULL){printf("[%d]", temp->data);temp = temp->next;}printf("\n");}}/* 入栈,从头部插入 */void push(int value){if (stack){pNode newnode;newnode = (pNode)malloc(sizeof(s_node)); if (!newnode){printf("malloc fail, please check!");return;}newnode->data = value;newnode->next = stack;stack = newnode;++pCount;}else{stack = (pNode)malloc(sizeof(s_node));if (!stack){printf("malloc fail, please check!");return;}stack->data = value;stack->next = NULL;++pCount;}}/* 出栈,从头部删除 */void pop(int *value){pNode top;if (stack != NULL){top = stack;stack = stack->next;*value = top->data;free(top);--pCount;}else{pCount = 0;}}void main(){pNode point;int select;int value;printf("(1)Input a stack data.\n");printf("(2)Output a stack data.\n");printf("(3)Exit\n");printf("Please select your choice: ");scanf("%d", &select);do{switch (select){case 1:printf("Before push, the stack content (top->bottom) is: \n");print_stack(); /* 打印栈的内容 */printf("Please input the digit: ");scanf("%d", &value);push(value);printf("After push, the stack content (top->bottom) is: \n");print_stack();break;case 2:printf("Before pop, the stack content (top->bottom) is: \n");print_stack(); /* 打印栈的内容 */if (pCount) {pop(&value);printf("The output value is: [%d].\n", value);printf("After pop, the stack content (top->bottom) is: \n");print_stack();}else{printf("The stack is empty, it can not be poped!");}break;default:printf("Please input the right choice!");break;}printf("\n(1)Input a stack data.");printf("\n(2)Output a stack data.");printf("\n(3)Exit.");printf("\nPlease select your choice: ");scanf("%d", &select);} while (select != 3);}
运行结果如下所示:
0 0
- 数据结构示例之用链表实现栈
- 数据结构示例之用链表实现顺序队列
- 数据结构示例之使用数组实现栈
- 数据结构示例之数组模拟多栈实现
- 数据结构示例之顺序数组的实现
- 数据结构示例之用数组实现圆形队列
- 数据结构之栈实现
- 数据结构实现之栈
- 数据结构示例之数组翻转
- 数据结构示例之阶乘计算
- 数据结构示例之复制字符串
- 数据结构示例之字符串替换
- 数据结构示例之字符串比较
- 数据结构示例之分割字符串
- 数据结构示例之连接字符串
- 数据结构之list(用链表实现)
- 数据结构之顺序栈实现
- 数据结构之链栈实现
- A Discriminative Feature Learning Approach for Deep Face Recognition, ECCV16.
- Android之内存泄露LeakCanary检测
- 快速排序
- 第82篇 webrtc一对一研究(十)及php
- 最简单的webview监听及传值
- 数据结构示例之用链表实现栈
- Linux命令之"df"
- 将一个链表中结点的值按奇偶拆分,使其中一个链表结点的值为偶数,另一个为奇数
- canvas学习笔记(一)——关于css设置canvas画布大小的问题
- 逻辑回归
- Appium For Android and IOS By Java
- 微信的开发之初学问题总结
- Java_socket通信基础补充
- Windows10专业版任务栏右下角按钮左键无效右键有效的问题的解决