#include<iostream>
#include<ctime>
#include<cstdlib>
#include<fstream>
using namespace std;
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Stack;
typedef PtrToNode Position;
//创建栈节点
struct Node
{
int element;//节点数据域
PtrToNode next;//指针域
PtrToNode pre;//当前节点的前一个节点的地址
};
//创建栈
Stack CreateStack()
{
Stack S = (PtrToNode)malloc(sizeof(struct Node));
if (S == NULL)
{
cout << "分配内存失败!" << endl;
return S;
}
else
{
//初始化
S->next = NULL;
S->pre = NULL;
S->element = -1;
return S;
}
}
//判断栈是否为空
int IsEmpty(Stack S)
{
return S->next == NULL;
}
//将数据输入到栈中
int Push(int X, Stack& S)
{
PtrToNode TmpCell;
TmpCell = (PtrToNode)malloc(sizeof(struct Node));//开辟一个空间存储
if (TmpCell == NULL)
return -1;
else
{
TmpCell->element = X;
if (S->element == -1)
{
TmpCell->pre = NULL;//如果是第一个进栈的,则它的pre为NULL,不为S
}
else
{
TmpCell->pre = S;
}
//尾插法
S->next = TmpCell;
S = TmpCell;
S->next = NULL;
return 0;
}
}
//将数据保存到文件中
void Pop2Txt(Stack& S)
{
ofstream outRes;
outRes.open("chu.txt");
int num;
Position p = S;
while (p!=NULL)//通过pre回溯读取数据并输出到文件中
{
outRes << p->element << " ";
p = p->pre;
}
outRes.close();
cout << "存储成功!" << endl;
}
//输出栈中的内容(倒流输出,与输入到文件中的数据顺序一致)
void Show(Stack& S)
{
Position p = S;
if (p == NULL)
cout << "栈已空!" << endl;
else
{
while (p != NULL)
{
cout << p->element << " ";
p = p->pre;
}
}
cout << endl;
}
int main()
{
srand(time(0));//生成随机数种子
ofstream output;
output.open("jin.txt");
int T = 100 + 5;
while (T--)
{
int num = rand() % 100;
output << num << " ";
}
output.close();
ifstream input;
input.open("jin.txt");
Stack s;
s = CreateStack();
int a = 105;
int tmp;
while (a--)
{
input >> tmp;
Push(tmp, s);
}
input.close();
//展示站内的数据
Show(s);
//将数据保存到文件中
Pop2Txt(s);
return 0;
}
尾插法实现栈
最新推荐文章于 2022-11-24 01:43:35 发布