转载
typedef
typedef struct ListNode {
int value;
struct ListNode *next;(这里不能用listnode*应为还没有定义)
} ListNode;
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int value;
struct ListNode *next;
};
// 创建新节点函数
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 头插法添加节点函数
void insertAtHead(struct ListNode** head, int value) {
struct ListNode* newNode = createNode(value);
newNode->next = *head;
*head = newNode;
}
// 删除节点函数
void deleteNode(struct ListNode** head, int value) {
struct ListNode* temp = *head;
struct ListNode* prev = NULL;
// 如果头节点就是要删除的节点
if (temp != NULL && temp->value == value) {
*head = temp->next; // 改变头指针
free(temp); // 释放旧的头节点内存
return;
}
// 查找要删除的节点
while (temp != NULL && temp->value != value) {
prev = temp;
temp = temp->next;
}
// 如果节点不存在
if (temp == NULL) return;
// 删除节点
prev->next = temp->next;
free(temp);
}
// 查找节点函数
struct ListNode* findNode(struct ListNode* head, int value) {
struct ListNode* current = head;
while (current != NULL) {
if (current->value == value) {
return current;
}
current = current->next;
}
return NULL;
}
int main() {
struct ListNode* head = NULL;
// 使用头插法添加节点
insertAtHead(&head, 3);
insertAtHead(&head, 2);
insertAtHead(&head, 1);
// 查找节点
struct ListNode* foundNode = findNode(head, 2);
if (foundNode != NULL) {
printf("Found node with value: %d\n", foundNode->value);
} else {
printf("Node with value 2 not found.\n");
}
// 删除节点
deleteNode(&head, 2);
// 遍历链表以验证删除操作
struct ListNode* current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
return 0;
删除节点/释放节点
先改接 后删除 (应为改接要利用那个节点,且链表单向不可逆向访问)
释放链表 把每个节点都free
注意点
0typedef struct node里面 的next要用
struct node* next不能用别名
还没取出来
1malloc头文件stdlib
2操作的都是指针 都要用->
3用listnode* nodestr[5] = {NULL};存指针
不用listnode**还要动态管理malloc 麻烦
函数返回值返回指针
4指针是判断NULL
5删除节点的时候要获取prev
所以用p->next->value来判定
并且越界会导致程序跑不起来 必须做越界判断
双向链表
s->next=head->next
head->next=s
s->prev=head
head->next->prev=s
双向链表插入一个节点
next右向的从右边连到左边
右边的赋值给左边
反之