用C语言创建一个由6个结点的单向链表,实现增加、删除、查找、移动、显示结点的基本功能。
时间: 2023-12-21 18:04:29 浏览: 73
单向链表,包括创建、插入、删除等基本操作
可以的,以下是C语言实现的代码示例:
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建节点
Node* createNode(int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
// 增加节点
void addNode(Node **head, int data) {
Node *newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node *tail = *head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = newNode;
}
// 删除节点
void deleteNode(Node **head, int data) {
if (*head == NULL) {
return;
}
Node *pre = NULL;
Node *current = *head;
while (current != NULL) {
if (current->data == data) {
if (pre == NULL) {
*head = current->next;
} else {
pre->next = current->next;
}
free(current);
return;
}
pre = current;
current = current->next;
}
}
// 查找节点
Node* findNode(Node *head, int data) {
Node *current = head;
while (current != NULL) {
if (current->data == data) {
return current;
}
current = current->next;
}
return NULL;
}
// 移动节点
void moveNode(Node **head, int data, int index) {
if (*head == NULL) {
return;
}
Node *node = findNode(*head, data);
if (node == NULL) {
return;
}
deleteNode(head, data);
if (index == 0 || *head == NULL) {
node->next = *head;
*head = node;
} else {
Node *current = *head;
int i = 1;
while (current->next != NULL && i < index) {
current = current->next;
i++;
}
node->next = current->next;
current->next = node;
}
}
// 显示所有节点
void displayNodes(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 主函数
int main() {
Node *head = NULL;
addNode(&head, 1);
addNode(&head, 2);
addNode(&head, 3);
addNode(&head, 4);
addNode(&head, 5);
addNode(&head, 6);
displayNodes(head); // 显示所有节点:1 2 3 4 5 6
deleteNode(&head, 3);
deleteNode(&head, 6);
displayNodes(head); // 显示所有节点:1 2 4 5
moveNode(&head, 1, 3);
moveNode(&head, 5, 0);
moveNode(&head, 4, 1);
displayNodes(head); // 显示所有节点:5 4 1 2
Node *node = findNode(head, 1);
if (node != NULL) {
printf("找到节点: %d\n", node->data);
} else {
printf("未找到节点\n");
}
return 0;
}
阅读全文