数据结构1_顺序表

#include<stdio.h>
#include<stdlib.h>
#define maxsize 5

typedef int ElemType;

typedef struct
{
    ElemType * head;
    int length;
    int size;
} Table;

Table initTable()
{
    Table t;
    t.head = (ElemType *)malloc(sizeof(ElemType)*maxsize);
    if(!t.head)
    {
        printf("初始化失败!\n");
        exit(0);
    }
    t.length = 0;
    t.size = maxsize;
    return t;
}

//插入元素
Table insertElem(Table t, int add, ElemType elem)
{
    if(add<1 || add>t.length+1)
    {
        printf("插入元素失败!\n");
        return t;
    }
    
    if(t.length == t.size)
    {
        t.head = (ElemType *)realloc(t.head, sizeof(ElemType)*(t.size+1));
         if(!t.head)
        {
            printf("空间重分配失败!\n");
            return t; 
        }
        t.size +=1;
    }
    
    for(int i=t.length; i>add-1; --i)
    {
        t.head[i] = t.head[i-1];
    }
    
    t.head[add-1] = elem;
    
    t.length +=1;
    
    return t;
} 

//查找元素
int selectElem(Table t, ElemType elem)
{
    for(int i=0; i<t.length; ++i)
    {
        if(t.head[i] == elem)
            return ++i;
    }
    
    return 0;
}

//删除元素
Table deleteElem(Table t, ElemType elem)
{
    int add = selectElem(t, elem);
    
    if(add == 0)
    {
        printf("删除元素不存在!\n");
        return t; 
    }
    
    for(int i=add-1; i<t.length; ++i) 
        t.head[i] = t.head[i+1];
        
    t.length -=1;
    
    return t;
}

//修改元素 
Table modifyElem(Table t, ElemType elem1, ElemType elem2)
{
    int add = selectElem(t, elem1);
    
    if(add == 0)
    {
        printf("修改的元素不存在!\n");
        return t; 
    }
    
    t.head[add-1] = elem2; 
    
    return t;
}

//遍历元素 
void traverse(Table t)
{
    for(int i=0; i<t.length; ++i)
    {
        printf("%-4d",t.head[i]);
    }    
    
    printf("\n");
}

int main(void)
{
    Table t;
    t = initTable();
    
    for(int i=0; i<maxsize; ++i)
    {
        t.head[i] = i;
        t.length++;
    }
    
    traverse(t);
    
//    t = insertElem(t,1,34);
//    printf("%d\n",selectElem(t, 5));
    
//    t = deleteElem(t, 6);
    t=modifyElem(t,6, 23);
    traverse(t);
    
    return 0;
    
}

 

posted @ 2020-07-13 03:22  陌上尘如玉  阅读(87)  评论(0)    收藏  举报