1. 创建链表
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *createList() {
struct ListNode *head = NULL, *tail = NULL;
int num;
scanf("%d", &num);
while (num!= -1) {
struct ListNode *newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode->val = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
scanf("%d", &num);
}
return head;
}
2. 遍历链表
void printList(struct ListNode *head) {
struct ListNode *cur = head;
while (cur!= NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
3. 查找节点(查找值为特定值的节点)
struct ListNode *findNode(struct ListNode *head, int target) {
struct ListNode *cur = head;
while (cur!= NULL) {
if (cur->val == target) {
return cur;
}
cur = cur->next;
}
return NULL;
}
4. 插入节点(在指定节点后插入新节点)
void insertNodeAfter(struct ListNode *prevNode, int newVal) {
if (prevNode == NULL) {
return;
}
struct ListNode *newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode->val = newVal;
newNode->next = prevNode->next;
prevNode->next = newNode;
}
5. 删除节点(删除值为特定值的节点)
struct ListNode *deleteNode(struct ListNode *head, int target) {
struct ListNode *prev = NULL;
struct ListNode *cur = head;
while (cur!= NULL && cur->val!= target) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) {
return head;
}
if (prev == NULL) {
head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
return head;
}
主函数(用来测试函数):
int main() {
struct ListNode *head = createList();
printf("原始链表: ");
printList(head);
struct ListNode *foundNode = findNode(head, 3);
if (foundNode!= NULL) {
printf("找到值为 3 的节点\n");
} else {
printf("未找到值为 3 的节点\n");
}
if (foundNode!= NULL) {
insertNodeAfter(foundNode, 5);
printf("插入节点后链表: ");
printList(head);
}
head = deleteNode(head, 3);
printf("删除节点后链表: ");
printList(head);
struct ListNode *cur = head;
while (cur!= NULL) {
struct ListNode *next = cur->next;
free(cur);
cur = next;
}
return 0;
}