线性表的基本操作代码C
时间: 2024-10-08 14:27:02 浏览: 31
线性表(c语言代码)
线性表是一种基本的数据结构,它由一系列元素组成,并通过链接的方式存储,每个元素都有一个前驱和后继节点。在C语言中,我们通常可以使用数组或链表来实现线性表。这里提供一些基本操作的示例:
1. **创建动态链表头指针** (单链表)
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList() {
Node* head = NULL; // 初始化空链表
return head;
}
```
2. **在链表尾部添加元素**
```c
void append(Node** head, int value) {
if (*head == NULL) {
*head = (Node*)malloc(sizeof(Node)); // 如果链表为空,新建一个节点
(*head)->data = value;
(*head)->next = NULL;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = (Node*)malloc(sizeof(Node));
temp->next->data = value;
temp->next->next = NULL;
}
}
```
3. **删除指定位置的元素**
```c
void deleteElement(Node** head, int index) {
if (*head == NULL) {
return;
}
Node* current = *head;
Node* previous = NULL;
if (index == 0) {
*head = current->next;
free(current);
} else {
for (int i = 0; i < index - 1 && current != NULL; i++) {
previous = current;
current = current->next;
}
if (current == NULL) { // 越界情况处理
printf("Invalid index");
return;
}
previous->next = current->next;
free(current);
}
}
```
4. **遍历线性表**
```c
void traverse(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
} else {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}
```
阅读全文