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

本文介绍了线性表的两种表示方法:顺序表示和链式表示。顺序表示通过结构体和定长数组实现,而链式表示采用单链表结构,每个节点包含数据和指向下一个节点的指针。提供了相应的C语言实现代码,并邀请读者对可能存在的问题进行反馈。
摘要由CSDN通过智能技术生成

线性表的顺序表示

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

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值