数据结构上机实验(1) 顺序线性表

来源:互联网 发布:画动漫的软件 编辑:程序博客网 时间:2024/06/07 07:27
#include "stdafx.h"#include "malloc.h"#include "stdlib.h"#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0#define OVERFLOW -2typedef char ElemType;typedef int Status;typedef struct{    ElemType *elem;    int length;    int listsize;}SqList;Status InitList_Sq(SqList &L){    L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));    if (!L.elem)        exit(OVERFLOW);    L.length = 0;    L.listsize = LIST_INIT_SIZE;    return OK;}Status InsertList_Sq(SqList &L, int i, ElemType e){    ElemType *newbase, *p, *q;    if (i<1 || i>L.length + 1)        return ERROR;    if(L.length>=L.listsize){        newbase = (ElemType *)realloc(L.elem, (LIST_INIT_SIZE + LIST_INCREMENT)*sizeof(ElemType));        if (!newbase)            return ERROR;        L.elem = newbase;        L.listsize += LIST_INCREMENT;    }    q = &(L.elem[i - 1]);    for (p = &(L.elem[L.length - 1]); p >= q; p--)        *(p + 1) = *p;    *q = e;    ++L.length;    return OK;}Status DeleteList_Sq(SqList &L, int i, ElemType &e) {    ElemType *p, *q;    if (i<1 || i>L.length)        return ERROR;    p = &(L.elem[i - 1]);    e = *p;    q = L.elem + L.length - 1;    for (++p; p <= q; ++p)        *(p - 1) = *p;    --L.length;    return OK;}int LocateElem_Sq(SqList &L, ElemType e){    ElemType *p;    int i = 1;    p = L.elem;    while (i <= L.length && *p++ != e)        ++i;    if (i <= L.length)        return i;    else        return 0;}void MergeList_Sq(SqList La, SqList Lb, SqList &Lc){    ElemType *pa, *pb, *pc, *pa_last, *pb_last;    pa = La.elem;    pb = Lb.elem;    Lc.listsize = Lc.length = La.length + Lb.length;    pc = Lc.elem = (ElemType *)malloc(Lc.listsize * sizeof(ElemType));    if (!Lc.elem)        exit(OVERFLOW);    pa_last = La.elem + La.length - 1;    pb_last = Lb.elem + Lb.length - 1;    while(pa<=pa_last && pb<=pb_last){        if (*pa < *pb)            *pc++ = *pa++;        else            *pc++ = *pb++;    }    while (pa <= pa_last)        *pc++ = *pa++;    while (pb <= pb_last)        *pc++ = *pb++;}void display(SqList L){    int i;    for (i = 0; i <= L.length - 1; i++)        printf("%d\n", L.elem[i]);} int main(){    SqList L;    InitList_Sq(L);    InsertList_Sq(L, 1, 10);    InsertList_Sq(L, 2, 20);    InsertList_Sq(L, 1, 30);    InsertList_Sq(L, 3, 40);    printf("插入后:\n");    display(L);    InsertList_Sq(L, 3, 100); // 在L第三个位置插入100    printf("插入后:\n");    display(L);    ElemType e;    DeleteList_Sq(L, 3, e);    display(L);    printf("被删除元素:%d\n\n\n\n", e);    SqList La, Lb, Lc;    InitList_Sq(La);    InsertList_Sq(La, 1, 3);    InsertList_Sq(La, 2, 5);    InsertList_Sq(La, 3, 7);    InsertList_Sq(La, 4, 9);    InitList_Sq(Lb);    InsertList_Sq(Lb, 1, 4);    InsertList_Sq(Lb, 2, 6);    InsertList_Sq(Lb, 3, 8);    MergeList_Sq(La, Lb, Lc);    printf("归并后:\n");    display(Lc);    printf("\n");    int a = LocateElem_Sq(Lc, 4);    printf("数字:%d", a);    getchar();}
0 0
原创粉丝点击