写博客前的感想:
我是一名2017级的大二学生,大一的我虽然学的是计算机专业,但是非常不喜欢写代码,看见代码就脑阔疼,现在上数据结构却让我喜欢上了写代码,甚至是迷恋上了写代码,喜欢那种写出来的满足与开心的感觉。所以在这里写博客欲抛砖引玉,希望大家能够不吝给我建议和意见,谢谢大家。
下面就把代码都给出来吧:
#include<iostream>
#include<cmath>
#include<vector>
#include<string>
#include<stdio.h>
#include<algorithm>
using namespace std;
class list
{
public:
void create(int n);
void del(int i); //x代表要删除下标
void insert(int x); //x代表要插入的下标
void paixu();
void nizhi();
void find_index(int x); //x表示元素
int get_s(int i); //i表示下标
void get_m(); //获取最值
private:
int *a, *b, *c;
int length;
int max, min;
int new_length;
};
void list::create(int n)
{
a = new int[n];
length = n;
cout << "请输入数组的元素:" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
}
void list::paixu()
{
int temp;
cout << "排序后的数组为:" << endl;
for (int i = 0; i < length; i++)
{
for (int j = i; j < length; j++)
{
if (a[j] < a[i])
{
temp = a[i]; a[i] = a[j]; a[j] = temp;
}
//cout << a[i] << " ";
}
cout << a[i] << " ";
//cout << '\n';
}
cout << endl;
}
void list::del(int x)
{
b = new int[length];
for (int k = 0; k < length; k++)
{
b[k] = a[k];
}
for (int i = x; i < length; i++)
{
b[i] = b[i + 1];
}
cout << "删除第" << x+1 << "个位置的数组为:" << endl;
for (int j=0; j < length - 1; j++)
{
cout << b[j] << " ";
}
cout << endl;
}
void list::insert(int x)
{
int n;
cout << "请输入要插入的元素个数:" << endl;
cin >> n;
c = new int[length + n];
new_length = length + n;
for (int i = 0; i < length+n; i++)
{
if (i >= length)
{
c[i] = 0;
}
else
{
c[i] = a[i];
}
}
for (int j = length - 1; j >= x; j--)
{
c[j + n] = c[j];
}
cout << "请输入要插入的第" << x << "位置后的元素:"<<endl;
for (int k = 0; k < n; k++)
{
cin >> c[x + k];
}
cout << "插入后的数组为:" << endl;
for (int count = 0; count < length + n; count++)
{
cout << c[count] << " ";
}
cout << "\n";
}
void list::get_m()
{
max = a[0]; min = a[0];
for (int i = 0; i < new_length; i++)
{
if (c[i] <= min)
{
min = c[i];
}
if (c[i] >= max)
{
max = c[i];
}
}
cout << "最大值:" << max<<endl;
cout << "最小值:" << min << endl;
}
void list::nizhi()
{
int i = 0;
int temp;
for (i; i < length / 2 ; i++)
{
temp = a[i]; a[i] = a[length - i-1]; a[length - i-1] = temp;
}
cout << "逆置后的数组为:" << endl;
for (int j = 0; j < length; j++)
{
cout << a[j] << " ";
}
cout << endl;
}
void list::find_index(int x)
{
cout << x << "的下标为:";
for (int i = 0; i < new_length; i++)
{
if (c[i] == x)
{
cout << i << " ";
}
}
cout << endl;
}
int list::get_s(int i)
{
cout << "第" << i + 1 << "个元素为:" << c[i] << endl;
return i;
}
int main()
{
list hwq;
hwq.create(6);
hwq.paixu();
hwq.del(3);
hwq.insert(2);
hwq.get_m();
hwq.nizhi();
hwq.nizhi();
hwq.find_index(5);
hwq.get_s(7);
system("pause");
return 0;
}
这个代码比较简单,但是我的c++在大一的时候基础打得并不是非常扎实,在大二才觉悟,所以可能会有一些不合理的地方,所以请大家谅解。