#include<iostream> using namespace std;#define MAXSIZE 20 typedef int ElemType; typedef struct { ElemType data[MAXSIZE]; int length; } SqList; /* 初始化順序線性表 */ bool InitList(SqList *ptr) { for (int i = 0 ; i < MAXSIZE; i++) ptr->data[i] = 0; ptr->length = 0; return true; } bool ListEmpty(SqList Sq) { if (Sq.length == 0) return true; else return false; } bool ClearList(SqList *ptr) { for (int i = 0 ; i < ptr->length; i++) ptr->data[i] = 0; ptr->length = 0; return true; } /*用ptr返回Sq中第pos個資料元素的值,注意pos是指位置,第1個位置的數組是從0開始 */ bool GetElem(SqList Sq, int pos, ElemType *ptr) { if (Sq.length == 0 || pos < 1 || pos > Sq.length) return false; *ptr = Sq.data[pos - 1]; return true; } /*返回Sq中第1個與Elem滿足關係的資料元素的位序,若這樣的資料元素不存在,則傳回值為0 */ int Locate(SqList Sq, ElemType Elem) { for (int i = 0; i < Sq.length; i++) { if (Sq.data[i] == Elem) return i + 1; } return 0; } /*在Sq中第pos個位置之前插入新的資料元素Elem,L的長度加1*/ bool ListInsert(SqList *ptr, int pos, ElemType Elem) { if (ptr->length == MAXSIZE)/* 順序線性表已經滿 */ return false; if (pos < 1 || pos > ptr->length + 1) return false; if (pos <= ptr->length) { /* 將要插入位置之後的資料元素向後移動一位 */ for (int i = ptr->length - 1; i >= pos - 1; i--) { ptr->data[i + 1] = ptr->data[i]; } } ptr->data[pos - 1] = Elem; /* 將新元素插入 */ ptr->length++; return true; } /*刪除ps的第pos個資料元素,並用pe返回其值,ps的長度減1*/ bool ListDelete(SqList *ps, int pos, ElemType *pe) { if (pos < 1 || pos > ps->length) return false; *pe = ps->data[pos - 1]; /* 將刪除位元置後繼元素前移 */ for (int i = pos; i < ps->length; i++) ps->data[i - 1] = ps->data[i]; ps->length--; return true; } int ListLength(SqList Sq) { return Sq.length; } /*將所有線上性表pb中但不在pa中的元素都插入到pa中*/ void UnionList(SqList *pa, SqList *pb) { int lena = pa->length; int lenb = pb->length; int item; for (int i = 0; i < lenb; i++) { if (GetElem(*pb, i + 1, &item)) { if (Locate(*pa, item) == 0) ListInsert(pa, ++lena, item); } } } int main(void) { SqList Sq; InitList(&Sq); for (int i = 1 ; i < 5; i++) ListInsert(&Sq, i, i); if (!ListEmpty(Sq)) { cout << "Sq: " << endl; for (int i = 0 ; i < ListLength(Sq); i++) cout << Sq.data[i] << ' '; } cout << endl; int pos = Locate(Sq, 2); if (pos != 0) { int result; ListDelete(&Sq, pos, &result); cout << "delete: " << result << endl; } if (!ListEmpty(Sq)) { cout << "Sq: " << endl; for (int i = 0 ; i < ListLength(Sq); i++) cout << Sq.data[i] << ' '; } cout << endl; SqList Sq2; InitList(&Sq2); for (int i = 1 ; i < 4; i++) ListInsert(&Sq2, i, 6); ListInsert(&Sq2, 4, 7); if (!ListEmpty(Sq2)) { cout << "Sq2: " << endl; for (int i = 0 ; i < ListLength(Sq2); i++) cout << Sq2.data[i] << ' '; } cout << endl; UnionList(&Sq, &Sq2); if (!ListEmpty(Sq)) { cout << "Sq: " << endl; for (int i = 0 ; i < ListLength(Sq); i++) cout << Sq.data[i] << ' '; } cout << endl; return 0; } |