线性表顺序存储结构下基本操作的实现,线性表链式存储结构下基本操作的实现C语言代码
时间: 2024-09-27 09:02:49 浏览: 45
线性表的两种常见存储结构——顺序存储(数组)和链接存储(链表)的基本操作各有特点:
**顺序存储(数组)**:
1. 创建数组线性表:
```c
#include <stdio.h>
typedef struct List {
int data;
struct List* next;
} Node;
// 创建并初始化数组列表
Node* create_array_list(int n) {
Node* list = (Node*)malloc(n * sizeof(Node));
for (int i = 0; i < n; i++) {
list[i].data = 0;
list[i].next = NULL;
}
return list;
}
```
2. 插入和删除操作(这里假设元素是整数,插入在头部):
```c
void insert_at_start(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
void delete_at_start(Node** head) {
if (*head != NULL) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
} else {
printf("List is empty.\n");
}
}
```
3. 遍历数组:
```c
void print_list(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
```
**链接存储(链表)**:
1. 创建单链表:
```c
Node* create_linked_list() {
Node* list = (Node*)malloc(sizeof(Node));
list->data = 0;
list->next = NULL;
return list;
}
void insert_at_start_linked(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
2. 删除节点:
```c
void delete_node(Node** head, int key) {
Node* curr = *head;
if (curr != NULL && curr->data == key) {
*head = curr->next;
free(curr);
return;
}
Node* prev = NULL;
while (curr != NULL && curr->data != key) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
prev->next = curr->next;
free(curr);
}
```
3. 遍历链表:
```c
void print_linked_list(Node* head) {
while (head != NULL) {
printf("%d ->", head->data);
head = head->next;
}
printf("NULL\n");
}
```
阅读全文