线性表之顺序存储结构--C实现创建增添删除遍历输出和原地逆转的完整代码
时间: 2024-10-16 17:16:40 浏览: 48
线性表的顺序存储结构通常是在一维数组中实现的,它可以高效地进行元素的访问、插入和删除操作。以下是C语言中实现顺序表的一些基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义顺序表节点结构体
typedef struct {
int data;
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建顺序表
Node* createList(int n) {
Node* head = (Node*)malloc(sizeof(Node)); // 创建头节点
if (!head) {
printf("Memory allocation failed.\n");
return NULL;
}
head->data = 0;
head->next = NULL;
for (int i = 1; i < n; ++i) { // 创建其他节点
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
free(head);
return NULL;
}
newNode->data = i;
newNode->next = head->next;
head->next = newNode;
}
return head;
}
// 添加元素到列表末尾
void appendList(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) { // 如果列表为空,直接作为头结点
*head = newNode;
return;
}
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// 删除指定位置的元素
void deleteElement(Node** head, int index) {
if (*head == NULL || index < 0) {
return;
}
if (index == 0) { // 删除头节点
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
for (int i = 0; i < index - 1 && current != NULL; ++i) {
current = current->next;
}
if (current == NULL) {
return; // 没有找到指定索引的节点
}
Node* toDelete = current->next;
current->next = toDelete->next;
free(toDelete);
}
// 遍历并打印顺序表
void printList(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 原地逆转顺序表
void reverseList(Node** head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
Node* prev = NULL;
Node* current = *head;
Node* nextTemp = NULL;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
*head = prev;
}
int main() {
int size = 5;
Node* list = createList(size);
// 添加、删除、遍历操作...
printList(list);
appendList(&list, 6);
deleteElement(&list, 2);
reverseList(&list);
printList(list);
return 0;
}
```
阅读全文