链表.......

1d5499f35a7e46338194e5046c122597.jpg

 f7b145a34655452b985548c0b3968195.jpg

 转载

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

46b22c9453704261a007cc19ba9bca02.jpg

 注意点

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右向的从右边连到左边

右边的赋值给左边

反之

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值