软基作业——顺序线性表的插入

来源:互联网 发布:淘宝店铺怎么绑定旺旺 编辑:程序博客网 时间:2024/06/08 11:14

题目如下:设线性表存放在向量A[1..MAXNUM]的前elenum个分量中,且递增有序。试写一算法,将x插入到线性表的适当位置上,以保持线性表的有序性。


我的程序如下:

1. test.c

#include "insert.h"#include <stdio.h>int main(void){    listtype list;    int i;    float elenum;        /* Initialize the list.*/    list.elenum = 0;    for (i = 0; i < 20; i++)    {        list.A[i] = i + 1;        list.elenum++;        printf("(%d):%f\t", i + 1, list.A[i]);    }    printf("\nThe length of the list:%d\n\n", list.elenum);        /* To test the insert function.*/    insert(&list, 0);    insert(&list, 6.5);    insert(&list, 50);        for (i = 0; i < 23; i++)        printf("(%d):%f\t", i + 1, list.A[i]);    printf("\nThe length of the list:%d\n\n", list.elenum);        return 0;}    


2.insert.h

/* avoid redefine.*/#ifndef INSERT_H#define INSERT_H/* C99 only*/#include <stdbool.h>#define MAXNUM 100/* Define the type of list here. */typedef struct list_type{    float A[MAXNUM];    /* The array.*/    int elenum;         /* The num of elements.*/}listtype;/* Only C99 have the bool type. With C89, we can use int.*/bool insert(listtype *list, float element);#endif


3.insert.c

#include "insert.h"#include <stdio.h>bool insert(listtype *list, float element){    int i, j;        /* Check whether the list is full.*/    if (list->elenum >= MAXNUM)    {        printf("The list is full so can't be inserted./n");        return false;       /* return a failure result.*/    }        /* search the location to insert.*/    for (i = 0; i < list->elenum; i++)        if (list->A[i] > element)            break;                for (j = list->elenum; j > i; j--)        list->A[j] = list->A[j-1];        list->A[i] = element;    list->elenum ++;    return true;}


另附makefile文件如下:

test.exe : test.o insert.o
gcc -o test.exe test.o insert.o
test.o : test.c insert.h
gcc -c test.c
insert.o : insert.c insert.h
gcc -c insert.c

运行效果如下


原创粉丝点击