Chapter 1 线性表的顺序表示(持续更新)
找数组中最小的数,并引用返回最小值及其下标
#include <iostream>
using namespace std;
#define MaxSize 5
typedef int Elemtype;
typedef struct Sqlist{
Elemtype data[MaxSize];
int length;
}Sqlist;
void find_Min(Sqlist &L,Elemtype &value,int &pos){
value = L.data[0];
pos = 0;
for (int i = 1; i < L.length; i++) {
if(L.data[i]<value){
value = L.data[i];
pos = i;
}
}
cout<<"此时数组中最小的数字是"<<value<<endl;
cout<<"最小数字的下标是"<<pos<<endl;
cout<<"最小数字的位置是 第"<<pos+1<<"位"<<endl;
}
int main() {
struct Sqlist L;
int a[5] = {4,3,2,5,9};
L.length = 5;
Elemtype val;
int p;
for(int i = 0; i<L.length;i++){
L.data[i] = a[i];
}
for(int i = 0; i<L.length;i++){
cout<<" "<< L.data[i]<<" "<<endl;
}
find_Min(L,val,p);
}
核心代码是:
void find_Min(Sqlist &L,Elemtype &value,int &pos){ value = L.data[0]; pos = 0; for (int i = 1; i < L.length; i++) { if(L.data[i]<value){ value = L.data[i]; pos = i; } } cout<<"此时数组中最小的数字是"<<value<<endl; cout<<"最小数字的下标是"<<pos<<endl; cout<<"最小数字的位置是 第"<<pos+1<<"位"<<endl; }
删除线性表中最小的元素并且最后的元素代替它的值
bool del_Min(Sqlist &L,Elemtype &value){
if(L.length == NULL){
return false;
}
int pos;
find_Min(L,value,pos);
int end = L.length - 1;
L.data[pos] = L.data[end];
L.length--;
cout<<"删除成功后的数组序列为:"<<endl;
for(int i = 0; i<L.length;i++){
cout<<" "<< L.data[i]<<" "<<endl;
}
return true;
}
swap 交换两个数
#include <iostream>
using namespace std;
typedef int Elemtype;
void swap(Elemtype &a,Elemtype &b){
Elemtype c;
c = a;
a = b;
b = c;
}
int main() {
Elemtype a = 1314,
b = 521;
cout<<"交换之前 a,b 的值分别是:"<<a<<","<<b<<endl;
swap(a,b);
cout<<"交换之后 a,b 的值分别是:"<<a<<","<<b<<endl;
}
reverse 逆转数组
#include <iostream>
using namespace std;
typedef int Elemtype;
#define Max 5
void swap(Elemtype &a,Elemtype &b){
Elemtype c;
c = a;
a = b;
b = c;
}
typedef struct {
Elemtype data[Max];
int length;
}Sqlist;
bool reverse(Sqlist &L){
if (L.length==0){
return false;
}
for(int i=0;i<L.length/2;i++){
int j = L.length-1-i;
swap(L.data[i],L.data[j]);
}
cout<<"逆置之后的数组是:"<<endl;
for(int i=0;i<L.length;i++){
cout<<L.data[i]<<" ";
}
return true;
}
void Random(int *a,int n,int l,int r)//生成范围在l~r的随机数
{
srand(time(0)); //设置时间种子
for(int i=0;i<n;i++){
a[i]=rand()%(r-l+1)+l;//生成区间r~l的随机数
}
}
int main() {
Elemtype a = 1314,
b = 521;
cout<<"交换之前 a,b 的值分别是:"<<a<<","<<b<<endl;
swap(a,b);
cout<<"交换之后 a,b 的值分别是:"<<a<<","<<b<<endl;
Sqlist L;
L.length = 5;
Random(L.data,L.length,0,10);
cout<<"逆转之前的数组为"<<endl;
for (int i = 0; i < L.length; ++i) {
cout<<L.data[i]<<" ";
}
reverse(L);
}