7单链表基本操作,含菜单,C语言实现
时间: 2024-09-30 17:04:27 浏览: 60
在C语言中,单链表是一种动态数据结构,主要用于存储一系列元素,并通过节点间的指针链接在一起。以下是七个常见的单链表操作,以及简单的函数示例和对应的菜单选项:
1. **创建链表(Create List)**:
```c
void createList() {
struct Node* head = NULL; // 创建头结点
}
```
2. **添加元素到链表头部(Add to Head)**:
```c
void addToHead(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = head;
head = newNode;
}
```
3. **添加元素到链表尾部(Add to Tail)**:
```c
void addToTail(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
}
```
4. **删除指定值的节点(Delete Node)**:
```c
void deleteNode(int data) {
struct Node* temp = head;
struct Node* prev = NULL;
if (temp != NULL && temp->data == data) {
head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return;
prev->next = temp->next;
free(temp);
}
```
5. **查找特定值(Find Node)**:
```c
struct Node* findNode(int data) {
struct Node* current = head;
while (current != NULL) {
if (current->data == data)
return current;
current = current->next;
}
return NULL;
}
```
6. **打印链表(Print List)**:
```c
void printList() {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
```
7. **释放链表内存(Free List)**:
```c
void freeList() {
struct Node* current = head;
struct Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
head = NULL;
}
```
**菜单选项**:
1. 创建链表
2. 添加元素到头部
3. 添加元素到尾部
4. 删除节点
5. 查找节点
6. 打印链表
7. 释放内存
8. 退出程序
阅读全文
相关推荐
















