尾插法实现栈

#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;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值