数据结构之链表的实现(C语言)

本博客记录了如何使用C语言去实现数据结构中的链表,下面将展示其代码的具体实现。

其中还有向链表插入节点、删除节点、遍历链表的相关方法。

代码中写了大量注释,便于大家理解

LinkedList.c

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

/*
    Insert: 往h指向的单链表中,增加一个结点p
        h指向一个升序链表,要求插入后的链表仍然升序。
    @h: 指向原单链表的第一个结点
    @p: 指向待加入的结点
    返回值:
        返回插入完成后链表的第一个结点的地址。
*/
Node*
Insert(Node*h, Node *p )
{
    if (h == NULL)
    {
        return p;
    }

    if (p == NULL)
    {
        return h;
    }

    if (p->data < h->data)
    {
        p->next = h;
        return p;
    }
    else 
    {
        h->next = Insert(h->next ,p);
        return h;
    }
}

/*
    print_list: (从第一个结点 到最后一个结点)打印链表上的每一个结点的值
    @h: 指向链表的第一个结点
    返回值:
        无。
*/
void print_list(Node *h)
{
    while (h)
    {
        printf("%d ", h->data);
        h = h->next;
    }
}


// 逆序(从最后一个结点开始)打印一个单链表
void p(Node *h)
{
    if (h == NULL)
    {
        return ;
    }

    //1. 先逆序打印后面那个链表
    p(h->next);

    //2. 再打印第一个结点
    printf("%d ", h->data);
}

int sum(Node* h)
{
    if (h == NULL)
    {
        return 0;
    }
    else
    {
        return h->data + sum(h->next);
    }

}


Node* delete_x(Node*h , DataType x)
{
    if (h == NULL)
    {
        return NULL;
    }

    if (h->data != x)
    {
       h->next = delete_x(h->next, x)  ;
       return h;
    }
    else //h->data == x
    {
        // 先删除结点 h
        Node *p = h->next;
        h->next = NULL;
        free(h);

        //再删除后面那个链表上值为x的结点
        //整个完成后,链表的第一个结点,应该为后面那个链表
        //的第一个结点

        return  delete_x(p, x);
    }

}

LinkedList.h

#ifndef __LINKEDLIST_H__
#define __LINKEDLIST_H__

typedef int DataType;

// "数据结点"
typedef struct Node
{
   DataType data;   // "数据域":保存数据元素的

   struct Node* next;    // "指针域":保存下一个数据元素的地址
}Node;


/*
    Insert: 往h指向的单链表中,增加一个结点p
        h指向一个升序链表,要求插入后的链表仍然升序。
    @h: 指向原单链表的第一个结点
    @p: 指向待加入的结点
    返回值:
        返回插入完成后链表的第一个结点的地址。
*/
Node*
Insert(Node*h, Node *p );

/*
    print_list: (从第一个结点 到最后一个结点)打印链表上的每一个结点的值
    @h: 指向链表的第一个结点
    返回值:
        无。
*/
void print_list(Node *h);

/*
    delete_x: 删除链表h上值为x的结点
    @h: 指向链表的第一个结点
    @x: 要删除的结点的值
    返回值:
        返回删除后的链表的第一个结点的指针
*/
Node*
delete_x(Node*h , DataType x);

#endif

链表的插入、删除节点测试用例

main.c

#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
int main()
{
    Node *h = NULL; //指向链表的第一个结点
    int d;

    while (1)
    {
        scanf("%d", &d);
        if (d == 0)
        {
            break;
        }
        //1.申请一个结点,保存数据d
        Node *p = (Node*)malloc(sizeof(Node)) ;
        p->data = d;
        p->next = NULL;

        // 2. 把p插入到h指向的升序链表中去
        h =  Insert(h, p) ;
    }

    print_list(h);

    int x;
    scanf("%d", &x);
    h = delete_x(h, x);
    print_list(h);

    return 0;
}

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值