栈(链表实现)
来源:互联网 发布:内置软件卸载工具 编辑:程序博客网 时间:2024/06/07 01:19
1.思路
节点结构体为:一个int数值,一个指向下一个节点的指针Struct* next。设定一个链表头节点p,每次入栈的节点都放在p点的下一个节点,前面的节点则依次往后推移一位;每次出栈时将p->next对应节点值输出,并将p->next指向p->next->next;当p->next为nullptr则表明栈为空;当p为nullptr,表明栈不存在。
2.代码
#include <iostream>using namespace std;struct Stack { int value; struct Stack *next;};Stack* CreateStack() { Stack* p = (Stack*)malloc(sizeof(Stack)); p->value = 0; p->next = nullptr; return p;}bool isEmpty(Stack* p) { if(p == nullptr) { cout << "stack creats failed" << endl; return true; } return p->next == nullptr;}Stack* PushStack(Stack* p, int value) { if(p == nullptr) { cout << "stack creats failed" << endl; return nullptr; } Stack* tmp = (Stack*)malloc(sizeof(Stack)); tmp->value = value; tmp->next = p->next; p->next = tmp; return p;}int PopStack(Stack* p) { if(p == nullptr) { cout << "stack creats failed" << endl; return -100000000; } Stack* tmp = p->next; p->next = tmp->next; int res = tmp->value; free(tmp); return res;}void Destroy(Stack* p) { while(!isEmpty(p)) { PopStack(p); } free(p); p = nullptr;}int main() { Stack* p = CreateStack(); cout << "push 0-9" << endl; for(int i = 0; i < 10; ++i) { p = PushStack(p, i); } cout << "pop stack until it's empty" << endl; while(!isEmpty(p)) { cout << PopStack(p) << endl; } cout << "push 22" << endl; p = PushStack(p, 22); cout << "push 6" << endl; p = PushStack(p, 6); cout << "push 11" << endl; p = PushStack(p, 11); cout << "pop" << endl; cout << PopStack(p) << endl; cout << "pop" << endl; cout << PopStack(p) << endl; cout << "push 8" << endl; p = PushStack(p, 8); cout << "pop" << endl; cout << PopStack(p) << endl; cout << "pop" << endl; cout << PopStack(p) << endl; Destroy(p); return 0;}
3.运行结果
阅读全文
0 0
- 栈(链表实现)
- 栈(链表实现)
- 栈(stack)C语言链表实现&&数组实现
- 用Java实现栈(Stack)之链表实现
- 栈的实现(数组与链表实现)
- 栈和队列的基本实现(数组实现和链表实现)
- Java栈实现:数组实现和链表实现
- 栈实现队列,链表实现栈
- 栈模型的实现--链表实现
- 栈---链表实现
- 栈--链表实现
- 栈-----------链表实现
- 链表实现栈
- 链表实现栈
- 链表实现栈
- 各种实现队列的问题:链表实现,栈实现队列及队列实现栈
- 简易栈模版(链表实现)
- 栈的链表实现(Java)
- Mac终端常用开发命令
- java小知识点
- java详解 --- 抽象与接口
- WCF 部署到IIS 上
- 剑指offer — 二叉树中的某一路径
- 栈(链表实现)
- flume串联的简单使用
- 周赛的题目—Scarborough Fair
- 12-11 网易实习一面
- android第三方支付,支付宝使用学习
- springboot+rabbitMq整合开发实战二:模拟用户下单的过程
- 一个设想:基于colinux,the user mode os/xaas for both realhw/langsys
- privacy
- Linux常用命令