c语言单链表基本操作代码,要求包含:初始化单链表,销毁单链表,判断单链表是否为空表,求单链表长度,输出单链表,求单链表中指定位置的某个元素的值,按元素值查找,单链表的插入算法,单链表上的删除算法,以上功能使用switch和case来制作一个功能菜单,要整型和字符型都能插入
时间: 2024-10-25 16:02:19 浏览: 45
用C语言实现单链表的各种操作(一)
在C语言中,我们首先需要定义链表节点结构体,然后实现一些基础操作。这里是一个简单的示例,展示了如何使用`struct`、`malloc`和`free`来进行链表的基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 整型数据
char data_char; // 字符型数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 初始化单链表
Node* initList() {
return (Node*) malloc(sizeof(Node));
}
// 销毁单链表
void destroyList(Node* head) {
if (head != NULL) {
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
}
// 判断单链表是否为空
int isEmpty(Node* head) {
return head == NULL;
}
// 获取单链表长度
size_t listLength(Node* head) {
size_t length = 0;
Node* current = head;
while (current != NULL) {
length++;
current = current->next;
}
return length;
}
// 输出单链表
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d - %c ", current->data, current->data_char);
current = current->next;
}
printf("\n");
}
// 查找指定索引元素
int getElementAt(int index, Node* head) {
Node* current = head;
for (size_t i = 0; i < index && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
return -1; // 索引超出范围
} else {
return current->data; // 返回元素值
}
}
// 插入整数
void insertInt(Node** head, int value) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 插入字符
void insertChar(Node** head, char value) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data_char = value;
newNode->next = *head;
*head = newNode;
}
// 功能菜单(仅用于演示,实际应用中应提供用户输入)
void menu() {
int choice;
Node* head = initList();
while (1) {
printf("1. Initialize List\n");
printf("2. Destroy List\n");
printf("3. Check If Empty\n");
printf("4. Get List Length\n");
printf("5. Print List\n");
printf("6. Get Element at Index (Integer)\n");
printf("7. Insert Integer\n");
printf("8. Insert Character\n");
printf("9. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: head = initList(); break;
case 2: destroyList(head); break;
case 3: printf("%s\n", isEmpty(head) ? "Empty" : "Not Empty"); break;
case 4: printf("List Length: %zu\n", listLength(head)); break;
case 5: printList(head); break;
case 6: int index; scanf("%d", &index); printf("Element: %d\n", getElementAt(index, head)); break;
case 7: int input_int; scanf("%d", &input_int); insertInt(&head, input_int); break;
case 8: char input_char; scanf(" %c", &input_char); insertChar(&head, input_char); break;
case 9: destroyList(head); exit(0); break;
default: printf("Invalid choice.\n");
}
}
}
int main() {
menu();
return 0;
}
```
阅读全文