不知道取什么好
算法与数据结构 题目4.3
题目
实验规则
- 长度n的序列(1-n)
- 判断 序列第一个数==当前最大值?
– 是,输出该数
– 否,放入末尾 - 要求:计算某个编号的数据在第几次被输出
设计思路
- 用环状链表来模拟序列,每个节点当作一个数据。
- 链表: 序号,数据,下一个节点的指针
- 判断当前数据==最大值数组的最大值?
– 真–>输出节点,计数器 + 1
– 假–>跳过节点(环状链表,跳过后直接在序列末尾) - 判断该节点==所求节点?
–真–>打印计数器的值(既该节点为第几次输出)
–假–>进入下一个节点
流程图
代码实现
#include<iostream>
//Node :store the number of the array
typedef struct Node {
int _num; // store the serial number of each number in the array
int _data; //store the number in the array
Node * _next; //point the next number
}NumNode;
class Num_Data {
public:
Num_Data();
Num_Data(const int &n,const int &m);
~Num_Data();
void DataDel(); //delete a number node from the array
void DataShow(); //show a number node from the array
void DataSort(int left, int right); //to sort all numbers in the array (QuickSort)
void DataStare(); //begin show
private:
NumNode * _preNum; //point a number node in this array
int * _maxNum; //save a oderly array
int _len; //the length of the array
int _num; //the No what you want to know
int _count; //a counter
};
Num_Data::Num_Data() {
_preNum = NULL;
_maxNum = NULL;
_len = 0;
_num = 0;
_count = 0;
}
Num_Data::Num_Data(const int &n,const int &m) {
if (n <= 0) return;
// get the length and number of this Array
_len = n;
_num = m;
_count = 0;
_maxNum = new int[n];
NumNode * temp;
_preNum = temp = new NumNode;
for (int i = 1; i < n; i += 1) {
temp->_next = new NumNode;
temp = temp->_next;
std::cin >> _maxNum[i - 1];
temp->_num = i;
temp->_data = _maxNum[i - 1];
}
temp->_next = _preNum;
_preNum->_num = n;
std::cin >> _maxNum[n - 1];
_preNum ->_data = _maxNum[n - 1];
DataSort(0, _len - 1);
}
Num_Data::~Num_Data() {
delete[] _maxNum;
if (_preNum) {
NumNode *pre, *las;
pre = _preNum;
las = pre->_next;
while (las != _preNum) {
delete pre;
pre = las;
las = pre->_next;
}
delete pre;
}
}
void Num_Data::DataDel() {
NumNode * temp = _preNum->_next;
_preNum->_next = temp->_next;
delete temp;
}
void Num_Data::DataShow() {
this->_count += 1;
DataDel();
}
void Num_Data::DataSort(int left,int right) {
if (left < right) {
int key = _maxNum[left];
int low = left;
int high = right;
while (low < high) {
while (low < high && _maxNum[high] <= key) {
high -= 1;
}
_maxNum[low] = _maxNum[high];
while (low < high && _maxNum[low] >= key) {
low += 1;
}
_maxNum[high] = _maxNum[low];
}
_maxNum[low] = key;
DataSort(left, low - 1);
DataSort(low + 1, right);
}
}
void Num_Data::DataStare() {
while (1) {
if (_preNum->_next->_data == _maxNum[_count]) {
if (_preNum->_next->_num == this->_num) {
std::cout << _count + 1;
break;
}
DataShow();
}
else
_preNum = _preNum->_next;
}
}
int main(void) {
int n, m;
std::cin >> n >> m;
Num_Data data(n, m);
data.DataStare();
return 0;
}
个人觉得
觉得自己可能写多了。
首先觉得自己代码可能写长了,简单的问题复杂化了。
接着快速排序部分没写好,没理解透快速排序。
最后希望各位给点意见。