您的位置:首页 > 理论基础 > 数据结构算法

利用顺序表的操作,实现以下函数: 1)从顺序表中删除具有最小值的元素并由函数返回被删除元素的值。空出的位置由最后一个元素填补,若顺序表为空则显示出错信息并退出运行。

2017-09-26 16:04 2181 查看
利用顺序表的操作,实现以下函数:
1)从顺序表中删除具有最小值的元素并由函数返回被删除元素的值。空出的位置由最后一个元素填补,若顺序表为空则显示出错信息并退出运行。

题目没有看上去那么简单,一遍就搞定,在我们学校老师判定是错误的。

(1)比如有多个的最小位数,则必须先删除第一位最小数,再由目前数组的最后一位数填补在空缺的位置

(2)然后继续判断,在数组中最小位数是否还有,然后重复步骤1,知道没有最小位数才算结束

代码如下:

// newhomework1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"iostream"
using namespace std;

int main()
{
int array[10] = { 1,6,8,1,2,3,5};
int minimum = 666;
int lastone=-888;
int i, j,rank=0,minuscount=0;//rank is the real length of the array, and the minuscount is the number of being deleted elements
int flag = 1;//the minimum still exists in the array

//output all the original array elements
for (i = 0; array[i]!=0; i++)
{
cout << array[i] << " ";
}
//find the minumum element and the last element
for (j = 0; array[j] != 0; j++)
{
if(array[j]<minimum)
{
minimum = array[j];
}
lastone = array[j];
rank++;
}

//when there's still any minimum elemnt in the array, it will continue
while (1)
{
flag = 0;
//delete the first minimum element, and move the last element to the empty adress
for (j = 0; array[j]!=0; j++)
{
if (array[j]==minimum)
{
array[j] = lastone;
flag = 1;
array[rank -1- minuscount] = 0;
minuscount++;
break;
}

}
if (flag == 0)
{
break;
}
//output the array which was changed
cout << endl;
for (i = 0; array[i] != 0; i++)
{
cout << array[i] << " ";
}

//refresh the last element
for (j = 0; array[j] != 0; j++)
{
lastone = array[j];
}

}

system("pause");
return 0;
}


输出过程和输出结果如图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐