美文网首页
c 链表使用

c 链表使用

作者: 激扬飞雪 | 来源:发表于2024-08-05 16:26 被阅读0次

1、Linkedlist.h

#ifndef __LINKED_LIST__
#define __LINKED_LIST__
typedef struct ListNode
{
    int data;
    struct ListNode *next;
    /* data */
} ListNode;

int add_node(int data);

int del_node(int data);

void printf_all_node();

int update_node(int old_data, int new_data);

#endif

2、Linkedlist.c

#include <stdio.h>
#include "Linkedlist.h"
#include <stdlib.h>

ListNode *head;

int add_node(int data) {
    ListNode *new_node = malloc(sizeof(ListNode));
    if (new_node == NULL) {
        printf("申请内存失败\n");
        return 0;
    }
    new_node->data = data;
    new_node->next = NULL;

    if (head == NULL) {
        head = new_node;
        printf("首次添加成功\n");
        return 1;
    }
    ListNode *cur = head;
    while (cur->next != NULL) {
        cur = cur->next;
    }
    cur->next = new_node;
    printf("非首次添加成功\n");
    return 1;
}

int del_node(int data) {
    ListNode *pre = NULL;
    ListNode *cur = head;
    while (cur != NULL) {
        if (cur->data == data) break;
        pre = cur;
        cur = cur->next;
    }
    if (cur == NULL) {
        printf("没有找到要删除的节点\n");
        return 0;
    }
    if (pre == NULL) {
        //要删除的是头结点
        head = cur->next;
        cur->next = NULL;
        free(cur);
        printf("删除成功是头结点\n");
        return 1;
    }
    pre->next = cur->next;
    cur->next = NULL;
    free(cur);
    printf("删除成功\n");
    return 1;
}

void printf_all_node() {
    ListNode *cur = head;
    while (cur != NULL) {
        printf("%d\n", cur->data);
        cur = cur->next;
    }
}

int update_node(int old_data, int new_data) {
    ListNode *cur = head;
    while (cur != NULL) {
        if (cur->data == old_data) {
            cur->data = new_data;
            printf("更新成功\n");
            return 1;
        }
        cur = cur->next;
    }
    printf("更新失败\n");
    return 0;

}

3、main.c

#include <stdio.h>
#include "Linkedlist.h"

int main() {
    add_node(10);
    add_node(20);
    add_node(30);
    add_node(100);
    add_node(50);
    printf_all_node();
    update_node(30, 90);
    printf_all_node();
    del_node(20);
    printf_all_node();
    del_node(10);
    printf_all_node();
    del_node(50);
    printf_all_node();
    return 0;
}

相关文章

网友评论

      本文标题:c 链表使用

      本文链接:https://www.haomeiwen.com/subject/ppgxkjtx.html