数据结构 | C语言实现线性表的顺序和链式结构

线性表的顺序表示

线性表的顺序表示,是通过构造一个结构体实现的。结构体内包含一个定长数组和一个顺序表的长度。一维数组可以是静态分配或者是动态分配的。这里使用的是静态分配的方法。
代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef int Position;
typedef struct LNode *List;

#define MAXSIZE 100

struct LNode{
   
    int Data[MAXSIZE];
    Position last;
};

List InitialList(){
   
    List L;
    L = (List) malloc(sizeof(List));
    L->last = -1;
    return L;
}

bool judgeEmpty(List L){
   
    if (L->last == -1) return true;
    else return false;
}

bool insert(List L, int element, int position){
   
    if (position < 0){
   
        printf("Error:插入的位置小于0\n");
        return false;
    }
    if (position >= MAXSIZE){
   
        printf("Error: 插入的位置超出最大长度\n");
        return false;
    }
    if (L->last >= MAXSIZE - 1){
   
        printf("Error:表已经满了,无法继续插入.\n");
    }
    for (int i = L->last; i >= position; i--){
   
        L->Data[i + 1] = L->Data[i];
    }
    L->Data[position] = element;
    L->last++;
    return true;
}

Position find(List L, int element){
   
    int i = 0;
    while(L->Data[i] != element && i <= L->last)
        i++;
    if (i == L->last) return -1;
    else return i;

}

bool deleteByIndex(List L, int index){
   
    if (L->last == -1){
   
        printf("The list is empty!\n");
        return false;
    }
    if (index < 0 || index > L->last){
   
        printf("Index is valid\n");
        return false;
    }
    for(int i = index; i < L->last + 1; i++){
   
        L->Data[i] = L->Data[i+1];
    }
    L->last--;
    return true;
}

bool deleteByElement(List L
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值