用c语言创建一个线性表并进行取值,查找,插入,删除
时间: 2024-10-20 13:17:53 浏览: 29
【数据结构与算法】线性表的重要基本操作与代码实现【C语言版】 定义线性表节点的结构.pdf
在C语言中,我们可以使用数组或链表来创建简单的线性表。这里我将演示如何使用结构体和动态链表来实现。
首先,定义一个结构体表示节点:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data; // 节点存储的数据
struct Node* next; // 指向下一个节点的指针
} Node;
```
接下来,创建链表的操作:
1. **初始化** (创建表):
```c
Node* createList() {
Node* head = NULL;
return head;
}
```
2. **取值** (访问特定位置的元素):
```c
int getValue(Node* list, int index) {
if (index < 0 || !list) {
printf("Index out of bounds.\n");
return -1;
}
Node* current = list;
for (int i = 0; i < index && current != NULL; ++i) {
current = current->next;
}
if (current == NULL) {
printf("Element not found.\n");
return -1;
}
return current->data;
}`
```
3. **插入** (在指定位置添加新元素):
```c
void insertValue(Node** head, int value, int index) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
if (index <= 0) {
newNode->next = *head;
*head = newNode;
return;
}
Node* temp = *head;
for (int i = 0; i < index - 1 && temp != NULL; ++i) {
temp = temp->next;
}
if (temp != NULL)
temp->next = newNode;
}
```
4. **删除** (移除特定位置的元素):
```c
void deleteValue(Node** head, int index) {
if (*head == NULL || index < 0) {
printf("Invalid operation.\n");
return;
}
if (index == 0) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* temp = *head;
for (int i = 0; i < index - 1 && temp != NULL; ++i) {
temp = temp->next;
}
if (temp == NULL || temp->next == NULL) {
printf("Element not found.\n");
return;
}
Node* toRemove = temp->next;
temp->next = toRemove->next;
free(toRemove);
}
```
阅读全文