1. 程式人生 > 其它 >10. C Pro 線性表的應用:求兩個集合的並集

10. C Pro 線性表的應用:求兩個集合的並集

1. File : list.h

#ifndef _LIST_H_

#define _LIST_H_
#include <stdlib.h>
#define LIST_INIT_SIZE 10
#define LISTINCREMENT 10

typedef int ElemType;
typedef struct {
  ElemType *elem;  // 儲存元素指標
  int length;      // list length == 已經使用的空間
  int size;      // 全連結串列的可用空間
} List;

int InitList(List &L);
void ListInsert(List &L, int i, ElemType e);   // 在第i個位置插入元素e
void ListDelete(List &L, int i, ElemType &e);  // 刪除第i個元素,並返回其值
void GetElem(List &L, int i, ElemType &e);  // 獲取第i個元素值
void DestroyList(List &L);         // 銷燬
void ClearList(List &L);            // 清空
int LocateElem(List &L, ElemType e, int compare); //返回第一個滿足某種關係的元素位置
int ListTempty(List &L);            // 線性表是否為空

#endif

2. File : list.cpp

#include "list.h"

int InitList(List &L){
  L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
  if (L.elem == NULL) exit(0);
  L.length = 0;
  L.size = LIST_INIT_SIZE;
  return 1;
}

void ListInsert(List &L, int i, ElemType e) {   // 在第i個位置插入元素e
  ElemType *p = NULL, *q = NULL, *temp = NULL;
  if (i<1 || i>L.length + 1) exit(0);
  if (L.length >= L.size) {
    temp = (ElemType*)realloc(L.elem, (L.size + LISTINCREMENT) * sizeof(ElemType));
    if (temp == NULL) exit(0);
    L.elem = temp;
    L.size += LISTINCREMENT;
  }
  p = &L.elem[i - 1];
  q = &L.elem[L.length - 1];
  while (q >= p) {
    *(q + 1) = *q;
    q--;
  }
  *p = e;
  ++L.length;
}

void ListDelete(List &L, int i, ElemType &e) {   // 刪除第i個元素,並返回其值
  ElemType *p = NULL, *q = NULL;
  if (i<1 || i>L.length + 1) exit(0);
  p = &L.elem[i - 1];
  e = *p;
  q = &L.elem[L.length - 1];
  while (p < q) {
    *p = *(++p);
  }
  --L.length;
}

void GetElem(List &L, int i, ElemType &e) {    // 獲取第i個元素值
  if (i<1 || i>L.length + 1) exit(0);
  e = L.elem[i - 1];
}

void ClearList(List &L) {
  memset(L.elem, 0, sizeof(List)*L.length);
  L.length = 0;
}

int ListTempty(List &L) {
  if (L.length == 0) return 1;
  return 0;
}

void DestroyList(List &L) {
  free(L.elem);
  L.length = 0;
  L.size = 0;
}

int LocateElem(List &L, ElemType e, int compare) {
  for (int i = 0; i < L.length; i++) {
    if (compare == 0 && e == L.elem[i]) return i + 1;
    if (compare < 0 && L.elem[i] <= e) return i + 1;
    if (compare > 0 && L.elem[i] >= e) return i + 1;
  }
  return 0;
}

3. File : combine.cpp

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main() {
  int i = 0;
  ElemType m = 0;
  List La, Lb;
  InitList(La);
  InitList(Lb);
  for (i = 1; i < 6; i++) {
    ListInsert(La, i, i);
    ListInsert(Lb, i, 2 * i);
  }
  for (i = 0; i < Lb.length; i++) {
    GetElem(Lb, i + 1, m);
    if (LocateElem(La, m, 0) == 0)
      ListInsert(La, La.length + 1, m);
  }

  for (i = 0; i < La.length; i++)
    printf("%d\t", La.elem[i]);

  getchar(); return 0;
}