集美大学课程实验报告-实验3:栈、队列与递归

集美大学课程实验报告-实验3:栈、队列与递归

项目名称 内容
课程名称 数据结构
班级 网安2413
指导教师 郑如滨
学生姓名 林沁茹
学号 202421336067
实验项目名称 实验3:栈、队列与递归
上机实践日期
上机实践时间 2学时

一、目的(本次实验所涉及并要求掌握的知识点)

以下内容请根据实际情况编写

  • 掌握STL中栈和队列的基本存储结构
  • 掌握STL中string的使用
  • 熟练掌握栈(stack)和队列(queue)的基本使用
  • 掌握栈和队列的一些典型应用

二、实验内容与设计思想

题目1:栈的应用

函数相关伪代码

数制转换
cin>>x
if(x==0)
|cout<<"0"
|return
else if(x<0)
|x=-x
|cout<<"-"
whilie(x!=0)
|t=x%8
|s1.pushu(t)
|x=x/8
end
while(!s1.empty())
|e=s1.top()
|s1.pop()
|cout>>e
end

函数代码

#include <iostream>
#include <stack>
using namespace std;   
int main()
{
	stack<int> s1;
	int n;
	cin >> n;
	if (n == 0) {
		cout << 0;
		return 0;
	}
	else if (n < 0) {
		cout << "-";
		n = -n;
	}
	while (n!=0)
	{
		s1.push(n % 8);
		n /= 8;
	}
	while (!s1.empty())
	{
		cout << s1.top();
		s1.pop();
	}
	return 0;
}

时间复杂度O(n),空间复杂度O(n)

题目2:递归程序编写

函数相关伪代码

while(x!=0)
|cin<<x
|s1.push(x)
end
while(!s1.empty())
|sum+=s1.top
|s1.pop()
end

函数代码

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	int sum=0,x;
	stack < int > s1;
	cin >> x;
	s1.push(x);
	while(x!=0)
	{
		cin >> x;
		s1.push(x);
	}
	while (!s1.empty())
	{
		sum += s1.top();
		s1.pop();
	}
	cout << sum << endl;
	return 0;
}

时间复杂度O(n),空间复杂度O(n)

题目3:队列的应用

函数相关伪代码

queue<int>q1,q2
int n,i,k
cin>>n
for(i=0;i<n;i++)
|cin>>k
|if(k%2)
||q1.push(k)
|else
||q2.push(k)
while(!q1.empty()&&!q2.empty())
|cout<<q1.front()
|q1.pop()
|if(!q1.empty())
||cout<<q1.front()
||q1.pop()
|cout<<q2.front()
|q2.pop()
end
while(!q1.empty())
|cout<<q1.front()
|q1.pop()
end
while(!q2.empty())
|cout<<q2.front()
|q2.pop()
end

函数代码

#include <iostream>
#include<queue>
#include<stack>
using namespace std;

int main()
{
    queue<int>q1, q2;
    int n,i,k;
    cin >> n;
    for (i = 0; i < n; i++) {
        cin >> k;
        if (k % 2) {
            q1.push(k);
        }
        else {
            q2.push(k);
        }
    }
    while (!q1.empty()&& !q2.empty()) {
        cout << q1.front()<<" ";
        q1.pop();
        if(!q1.empty()){
        cout << q1.front()<<" ";
        q1.pop();
        }
        cout << q2.front()<<" ";
        q2.pop();
    }
    
    while (!q2.empty()) {
        cout << q2.front();
        q2.pop();
        if(!q2.empty()){
            cout << " ";
}
    }
    
    while (!q1.empty()) {
        cout << q1.front();
        q1.pop();
        if(!q1.empty()){
            cout << " ";
}
    }
    return 0;
} 

时间复杂度O(n),空间复杂度O(n)

三、实验使用环境(本次实验所使用的平台和相关软件)

以下请根据实际情况编写


四、实验步骤和调试过程(实验步骤、测试数据设计、测试结果分析)

以下请根据实际情况编写

题目1:数制转换

本机运行截图
![本机截图]

PTA提交截图
![PTA提交截图]无

题目2:递归程序转化为非递归程序

本机运行截图
![本机截图]
PTA提交截图
![PTA提交截图]无

题目3:队列的应用

本机运行截图
![本机截图]

PTA提交截图
![PTA提交截图]


五、实验小结(实验中遇到的问题及解决过程、实验体会和收获)

以下请根据实际情况编写

遇到的问题及解决方法:

  1. 问题:程序崩溃找不到原因,终端崩溃
  • 解决方法:使用打断点进行调试的方法。
  1. 问题:代码缩进不规范。
  • 解决方法:使用visual studio修复代码。

实验体会和收获:

  • 学会了如何搭建C++开发环境。
  • 掌握了基本的代码调试方法。
  • 掌握了Visual Studio调试功能的基本使用

六、附件(参考文献和相关资料)

posted @ 2025-03-23 00:09  穗和  阅读(48)  评论(0)    收藏  举报