顺序表基本操作
记录简单的顺序表操作
#include "List.h" #include <stdlib.h> #include <iostream> void CreateList(SqList *&L, ElemType a[], int n) { int i; L = (SqList *)malloc(sizeof(SqList)); for (i = 0; i < n; i++) L->data[i] = a[i]; L->length = n; } void InitList(SqList *&L) { L = (SqList *)malloc(sizeof(SqList)); L->length = 0; } void DestroyList(SqList *&L) { free(L); } bool ListEmpty(SqList *L) { return (L->length == 0); } int ListLength(SqList *L) { return (L->length); } void DispList(SqList *L) { int i; for (i = 0; i < L->length; i++) { std::cout << L->data[i] << " "; } } bool GetElem(SqList *L, int i, ElemType &e) { if (i <1 || i >L->length) return false; e = L->data[i - 1]; return true; } int LocateElem(SqList *L, ElemType e) { int i = 0; while (i < L->length && L->data[i] != e) i++; if (i >= L->length) return 0; else return i + 1; } bool ListInsert(SqList *&L, int i, ElemType e) { int j; if (i < 1 || i > L->length + 1) return false; i--; for (j = L->length; j > i; j--) L->data[j] = L->data[j - 1]; L->data[i] = e; L->length += 1; return true; } bool listDelete(SqList *&L, int i, ElemType &e) { int j; if (i < 1 || i>L->length) return false; i--; e = L->data[i]; for (j = i; j < L->length - 1; j++) L->data[j] = L->data[j + 1]; L->length -= 1; return true; } void unionList(SqList *LA, SqList *LB, SqList *&LC) { int lena, i; ElemType e; InitList(LC); for (i = 1; i <= ListLength(LA); i++) { GetElem(LA, i, e); ListInsert(LC, i, e); } lena = ListLength(LA); for (i = 1; i <= ListLength(LB); i++) { GetElem(LB, i, e); if (!LocateElem(LA, e)) ListInsert(LC, ++lena, e); } }
1 #include <iostream> 2 #include "List.h" 3 using namespace std; 4 5 int main() { 6 7 SqList *A, *B, *C; 8 InitList(A); 9 InitList(B); 10 const int m = 5, n = 10; 11 int a[n]; 12 int b[m]; 13 cout << "Input 10 numbers for list A" << endl; 14 for (int i = 0; i < n; i++) { 15 cin >> a[i]; 16 } 17 18 CreateList(A, a, 10); 19 cout << "ListA:" << endl; 20 DispList(A); 21 22 cout << endl<<"Input 5 numbers for list B" << endl; 23 for (int i = 0; i < m; i++) { 24 cin >> b[i]; 25 } 26 CreateList(B, b, 5); 27 cout << "ListB:" << endl; 28 DispList(B); 29 cout << endl; 30 unionList(A, B, C); 31 cout << "ListC:" << endl; 32 DispList(C); 33 34 system("pause"); 35 }