矩阵(堆栈)

本文通过一个具体的C++程序实例,展示了如何使用栈结构存储二维数组中的元素,并实现特定位置元素的检索与相关计算。该程序首先将一个3x3的矩阵按行优先原则压入栈中,然后演示了如何根据坐标获取指定元素及其周边元素的求和。
摘要由CSDN通过智能技术生成
#include<iostream>
using namespace std;
typedef struct stack
{
	int date;
	stack* next;
};
int empty_stack(stack* top) //判断是否为空
{
	return (top == NULL);
}
stack* push_stack(stack* top, int date)//栈顶插入元素
{
	stack* p = new stack;
	p->date = date;
	p->next = top;
	top = p;
	return top;
}
void fun(stack *top,int i,int j) {
	//cout << top->date;
	int t = 9 - i * 3 - j-1;
	for (int n = 0; n < t; n++) {
		top = top->next;
	}
	cout << top->date;
}
int main() {
	int a[3][3] = {1,2,3,4,5,6,7,8,9};
	stack *top=new stack;
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			top = push_stack(top, a[i][j]);
		}
	}
	//cout << top->date;
	//cout << top->next->date;
	fun(top,0, 0);
	fun(top,0, 1);
	fun(top, 0, 2);
	fun(top, 1, 0);
	fun(top, 1, 1);
	fun(top, 1, 2);
	fun(top, 2, 0);
	fun(top, 2, 1);
	fun(top, 2, 2);
}

```cpp
#include<iostream>
using namespace std;
typedef struct stack
{
	int date;
	stack* next;
};
int empty_stack(stack* top) //判断是否为空
{
	return (top == NULL);
}
stack* push_stack(stack* top, int date)//栈顶插入元素
{
	stack* p = new stack;
	p->date = date;
	p->next = top;
	top = p;
	return top;
}
int fun(stack* top, int i, int j) {
	//cout << top->date;
	int t = 9 - i * 3 - j - 1;
	for (int n = 0; n < t; n++) {
		top = top->next;
	}
	return top->date;
}
int find(stack *top,int n) {
	int sum = 0;
	for (int i = 0; i < 3&&i+1<3; i++) {
		if (i == n)continue;
		cout<< fun(top, i, i + 1)<<" ";
			sum = sum + fun(top, i, i+1);
	}
	if (n != 2) {
		cout<< fun(top, 2, n)<<" ";
		sum=sum+ fun(top, 2, n);
	}
	return sum;
}
int main() {
	int a[3][3] = { 1,2,3,4,5,6,7,8,9 };
	stack* top = new stack;
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			top = push_stack(top, a[i][j]);
		}
	}
	cout <<find(top, 1) << endl;
	cout<<find(top, 2)<<endl;
	cout<<find(top, 0)<<endl;
	//cout << top->date;
	//cout << top->next->date;
	/*fun(top, 0, 0);
	fun(top, 0, 1);
	fun(top, 0, 2);
	fun(top, 1, 0);
	fun(top, 1, 1);
	fun(top, 1, 2);
	fun(top, 2, 0);
	fun(top, 2, 1);
	fun(top, 2, 2);*/

}
这里是从左到右(从上到下)依次入栈。我还是不够理解题目,值给代码吧,应该很容易看懂的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值