【数据结构】链栈
发布时间:2020-12-15 06:00:04 所属栏目:安全 来源:网络整理
导读:Lstack.h #pragma once #include iostream #include stdlib . h using namespace std; #define Elemtype inttypedef struct Nstack{ Elemtype data ; Nstack * next;}Node; //节点 typedef struct{ Node * top; int size;}Lstack; //栈结构 void Init(Lstack
Lstack.h #pragma once
#include<iostream>
#include <stdlib.h>
using namespace std;
#define Elemtype int
typedef struct Nstack
{
Elemtype data;
Nstack* next;
}Node;//节点
typedef struct
{
Node* top;
int size;
}Lstack;//栈结构
void Init(Lstack *st)
{
st->top = (Node*)malloc(sizeof(Node));
if (!st->top)
return;
st->top->next= NULL;
st->top = NULL;
st->size = 0;
}
void Push(Lstack *st,Elemtype &x)
{
Node* p = (Node*)malloc(sizeof(Node));
if (!p)
return ;
p->data = x;
p->next = st->top;
st->top = p;
st->size++;
}
bool Empty(Lstack *st)
{
return st->size==0;
}
void Pop(Lstack *st,Elemtype&e)
{
if (!Empty(st))
{
cout << "栈为空,不能删除!" << endl;
return;
}
Node*cur = st->top;
e = cur->data;
st->top = st->top->next;
free(cur);
st->size--;
}
void Gettop(Lstack *st,Elemtype &e)
{
if (!Empty(st))
{
cout << "栈为空,没有栈顶元素!" << endl;
return;
}
Node* temp = st->top;
e = st->top->data;
cout << "栈顶元素:" << e << endl;
}
void Length(Lstack *st)
{
cout << "栈长为:" << st->size << endl;
}
void Clear(Lstack *st)
{
if (Empty(st))
return;
st->size = 0;
Node* p=NULL;
while (st->top!=NULL)
{
p = st->top;
st->top = p->next;
free(p);
}
}
void Destroy(Lstack *st)
{
Clear(st);
free(st);
st = NULL;
}
void show(Lstack *st)
{
Node* p = st->top;
while (p)
{
cout << p->data;
p = p->next;
cout << "-->";
}
cout << "栈底"<< endl;
}
mian.cpp #include"Lstack.h"
void main()
{
Lstack q;
Elemtype item;
int select = 1;
while (select)
{
cout << "**********************************" << endl;
cout << "* [1] init [2] push *" << endl;
cout << "* [3] gettop [4] length *" << endl;
cout << "* [5] pop [6] clear *" << endl;
cout << "* [7] destroy [8] show *" << endl;
cout << "* [0] quit *" << endl;
cout << "**********************************" << endl;
cout << "please chose:>";
cin >> select;
switch (select)
{
case 1:
Init(&q);
break;
case 2:
cout << "请输入要入栈的元素:";
cin >> item;
Push(&q,item);
break;
case 3:
Gettop(&q,item);
break;
case 4:
Length(&q);
break;
case 5:
Pop(&q,item);
cout << "出栈元素为:" << item << endl;
break;
case 6:
Clear(&q);
break;
case 7:
Destroy(&q);
cout<<"栈已经被销毁!不能再插入数据!"<<endl;
return;
case 8:
show(&q);
break;
case 0:
cout << "退出成功!" << endl;
break;
default:
break;
}
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 调用Https WebService是报“基础连接已经关闭: 未能为 SSL/
- AngularJS学习:Providers
- 如何在angular2中加载一个域中的多个应用程序?
- vim 之自动缩进(smartindent) tab 空格数设置为4
- MiniProfiler:如何配置AngularJS WebAPI应用程序?
- vim – 我想在任何文本编辑器中更改文本内部表示的方式
- shell – 捕获由Makefile启动的后台进程的PID
- bash – 在sed命令中使用多行变量
- scala – 无形的类型转换
- ERROR in Cannot use 'in' operator to search