建立一个单链表,包含数据1,2,3,4,5,6,7,8八个数据,输出顺序表元素各值,输入要删除的元素,输出删除后的链表,输入将元素插入某个元素后的元素值,输出新链表,输入要修改的前后两个元素值,输出新链表。c语言完整代码
时间: 2024-10-23 11:12:25 浏览: 63
下面是一个简单的C语言示例,展示了如何创建单链表,删除节点、插入节点以及修改节点的操作。首先,我们需要定义链表节点结构和链表相关的函数。这里假设我们不使用头结点,直接从第一个节点开始。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新的链表节点
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 添加节点到链表末尾
void appendToList(Node** headRef, int value) {
Node* newNode = createNode(value);
if (*headRef == NULL) {
*headRef = newNode;
} else {
Node* temp = *headRef;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 删除节点
void deleteNode(Node** headRef, int value) {
Node* temp = *headRef;
Node* prev = NULL;
if (temp != NULL && temp->data == value) {
*headRef = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
// 插入节点
void insertNodeAfter(Node** headRef, int key, int value) {
Node* newNode = createNode(value);
Node* temp = *headRef;
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
if (temp == NULL) {
printf("Element not found\n");
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
// 修改节点值
void modifyNode(Node** headRef, int oldKey, int keyValue) {
Node* temp = *headRef;
while (temp != NULL) {
if (temp->data == oldKey) {
temp->data = keyValue;
break;
}
temp = temp->next;
}
}
// 打印链表
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 初始化链表并添加元素
for (int i = 1; i <= 8; ++i) {
appendToList(&head, i);
}
printf("Original List: ");
printList(head);
// 示例操作
int deleteValue = 5;
printf("Deleting %d from list...\n", deleteValue);
deleteNode(&head, deleteValue);
printf("List after deletion: ");
printList(head);
int insertValue = 4, keyValue = 9;
printf("Inserting %d after %d...\n", keyValue, insertValue);
insertNodeAfter(&head, insertValue, keyValue);
printf("List after insertion: ");
printList(head);
int modifyOldKey = 2, modifyNewKey = 7;
printf("Modifying element at index 2 to %d...\n", modifyNewKey);
modifyNode(&head, modifyOldKey, modifyNewKey);
printf("List after modification: ");
printList(head);
return 0;
}
```
这段代码演示了如何建立链表、删除节点、插入节点和修改节点。请注意,这个版本没有处理一些边界情况,实际使用时需要根据需求添加适当的错误检查。
阅读全文
相关推荐


















