数据结构--单向不循环链表C语言实现

头文件

#ifndef CPROJECT_LINK_H
#define CPROJECT_LINK_H

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

typedef int data_t;

typedef struct node{
    data_t data;
    struct node *next;
}node_t;

node_t *node_init();

void node_insert_behind(node_t *p, node_t *node);
void node_head_insert(node_t *p, data_t x);
void node_tail_insert(node_t *p, data_t x);
void node_delete(node_t *p, data_t x);
void node_update(node_t *p, data_t old, data_t new);
void node_show(node_t *p);


#endif //CPROJECT_LINK_H

实现文件

#include "../header/link.h"

node_t *node_init(){

    node_t *node = (node_t *) malloc(sizeof(node_t));

    if(node == NULL){
        perror("malloc");
        return NULL;
    }

    node->next = NULL;

    return node;
}

void node_insert_behind(node_t *p, node_t *node){

    node->next = p->next;
    p->next = node;

}

void node_head_insert(node_t *p, data_t x){

    node_t *node = node_init();
    node->data = x;

    node_insert_behind(p,node);

}

void node_tail_insert(node_t *p, data_t x){

    while (p->next != NULL)
        p = p->next;

    node_t *node = node_init();
    node->data = x;

    node_insert_behind(p,node);

}

void node_delete(node_t *p, data_t x){

    node_t *node = NULL;

    while (p->next != NULL){
        node = p->next;
        if(node->data == x){
            p->next = node->next;

            node->next = NULL;
            free(node);
        } else{
            p = p->next;
        }
    }

}

void node_update(node_t *p, data_t old, data_t new){

    node_t *node = NULL;
    node_t *new_node = NULL;

    while (p->next != NULL){
        node = p->next;
        if(node->data == old){
            new_node = node_init();
            new_node->data = new;

            new_node->next = node->next;
            p->next = new_node;

            node->next = NULL;
            free(node);
        }
        p = p->next;
    }
}

void node_show(node_t *p){

    while (p->next != NULL){
        printf("%d ",p->next->data);
        p = p->next;
    }
    printf("\n");

}

测试文件

#include "../header/link.h"

int main(){

    node_t *p = node_init();

    for (int i = 0; i < 5; ++i) {
        node_head_insert(p, i);
        node_tail_insert(p, i);
    }

    node_show(p);

    printf("*******************************\n");

    node_delete(p,0);

    node_show(p);

    printf("*******************************\n");

    node_update(p,2,100);

    node_show(p);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值