生成c语言数据结构线性表代码
时间: 2023-12-20 07:29:28 浏览: 97
以下是一个简单的C语言线性表的实现代码,包括顺序表和链表两种方式:
1. 顺序表实现
```c
#define MAXSIZE 100 // 定义线性表最大长度
typedef struct {
int data[MAXSIZE]; // 存储数据元素
int length; // 线性表当前长度
} SqList; // 顺序表类型定义
// 初始化线性表
void InitList(SqList *L) {
L->length = 0;
}
// 插入元素
bool ListInsert(SqList *L, int i, int e) {
if (i < 1 || i > L->length + 1 || L->length == MAXSIZE) {
return false; // 插入位置不合法或线性表已满
}
for (int j = L->length; j >= i; j--) {
L->data[j] = L->data[j - 1]; // 将插入位置后的元素后移
}
L->data[i - 1] = e; // 插入新元素
L->length++; // 线性表长度加1
return true;
}
// 删除元素
bool ListDelete(SqList *L, int i, int *e) {
if (i < 1 || i > L->length) {
return false; // 删除位置不合法
}
*e = L->data[i - 1]; // 将删除元素的值赋给e
for (int j = i; j < L->length; j++) {
L->data[j - 1] = L->data[j]; // 将删除位置后的元素前移
}
L->length--; // 线性表长度减1
return true;
}
// 查找元素
int LocateElem(SqList L, int e) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == e) {
return i + 1; // 返回元素在线性表中的位置
}
}
return 0; // 未找到元素
}
```
2. 链表实现
```c
typedef struct LNode {
int data; // 数据域
struct LNode *next; // 指针域
} LNode, *LinkList; // 链表类型定义
// 初始化链表
void InitList(LinkList *L) {
*L = (LinkList)malloc(sizeof(LNode)); // 创建头结点
(*L)->next = NULL; // 头结点指针域置空
}
// 插入元素
bool ListInsert(LinkList L, int i, int e) {
LNode *p = L, *s;
int j = 0;
while (p && j < i - 1) { // 寻找第i-1个结点
p = p->next;
j++;
}
if (!p || j > i - 1) {
return false; // 插入位置不合法
}
s = (LNode*)malloc(sizeof(LNode)); // 创建新结点
s->data = e; // 新结点赋值
s->next = p->next; // 新结点指向原第i个结点
p->next = s; // 原第i-1个结点指向新结点
return true;
}
// 删除元素
bool ListDelete(LinkList L, int i, int *e) {
LNode *p = L, *q;
int j = 0;
while (p->next && j < i - 1) { // 寻找第i-1个结点
p = p->next;
j++;
}
if (!p->next || j > i - 1) {
return false; // 删除位置不合法
}
q = p->next; // q指向第i个结点
*e = q->data; // 将删除元素的值赋给e
p->next = q->next; // 将第i-1个结点指向第i+1个结点
free(q); // 释放第i个结点的空间
return true;
}
// 查找元素
int LocateElem(LinkList L, int e) {
LNode *p = L->next;
int i = 1;
while (p) {
if (p->data == e) {
return i; // 返回元素在链表中的位置
}
p = p->next;
i++;
}
return 0; // 未找到元素
}
```
阅读全文
相关推荐
















