已知顺序表L递增有序,写一算法,将X插入到线性表的适当位置,以保持线性表的有序
已知顺序表L递增有序,写一算法,将X插入到线性表的适当位置,以保持线性表的有序,逆置。
本没有什么难度,可是写作业本上,不用DEBUG也还是出现了几个错误。
切忌眼高手低。
#include <iostream> #include <cstdio> #include <ctime> #include <cstdlib> #include <algorithm> using namespace std; #define MAX 1000 typedef int ElemType; typedef struct List{ int elem[MAX]; int last; }List; void CreateList(List *L) { for(int i = 0; i <= L->last; i++) { L->elem[i] = rand() % 100;//随机生成数据 } } void ShowList(List *L)//顺序表输出 { for(int i = 0; i <= L->last; i++) { cout << L->elem[i] << " "; } cout << endl; } void InsertList(List *L, ElemType e) { L->last++; int i, j; if(e <= L->elem[0]) { for(j = L->last; j >= 1; j--) { L->elem[j] = L->elem[j-1]; } L->elem[0] = e; } else if(e >= L->elem[L->last - 1]) { L->elem[L->last] = e; } else { for(i = 0; i < L->last; i++) { if(e >= L->elem[i] && e <= L->elem[i+1]) { for(j = L->last ; j >= i + 2; j--) { L->elem[j] = L->elem[j-1]; } L->elem[i+1] = e; break; } } } } void SortList(List *L) { sort(L->elem, L->elem + L->last + 1); } void ReverseList(List *L) { int i, j; ElemType e; j = L->last; for(i = 0; i <= j; i++,j--) { e = L->elem[i]; L->elem[i] = L->elem[j]; L->elem[j] = e; } } int main() { List L; ElemType e; L.last = 0; memset(L.elem, 0, sizeof(L.elem));//顺序表初始化 srand((unsigned)time(NULL)); int length = rand() % 10; cout << "元素的个数为:" << length << endl; L.last = length - 1; CreateList(&L);//顺序表建立 SortList(&L);//顺序表排序 cout << "插入元素之前:" << endl; ShowList(&L);//顺序表输出 cout << endl; e = rand() % 100;//随机确定生成数据的个数 cout << "插入的元素为:" << e << endl << endl; InsertList(&L, e);//输出表插入元素 cout << "插入元素之后:" << endl; ShowList(&L); cout << "逆置后的顺序表:" << endl; ReverseList(&L); ShowList(&L); }
Keep it simple!