单链表的逆置 --C语言泛型编程

本文章采用泛型算法实现了单链表的建立与逆置。代码如下:
一:头文件
#ifndef _LIST_H
#define _LIST_H

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

typedef struct list_node{
    void             *data;
    struct list_node *next;
} node_type, *node_ptr;

typedef struct link_list{
    node_ptr  head;
    size_t    size;                  //节点数
    void      (*destroy)(void *);    //链表析构函数,需要用户自定义
} list_type, *list_ptr;

void init_list(list_ptr lp, void (*destroy)())
{
    lp->head = (node_ptr)malloc(sizeof(node_type));
    lp->destroy = destroy;           //如果用户第二个参数传为NULL,那么不进行析构,会导致内存泄漏。
    lp->head->data = NULL;
    lp->head->next = NULL;
    lp->size = 0;
}

void insert_list(list_ptr lp, const void *elem)   //有头节点的方式建立链表,有利于后面算法的一致性
{
    assert(elem != NULL);

    node_ptr new_elem = (node_ptr)malloc(sizeof(node_type));   
    assert(new_elem != NULL);

    new_elem->data = (void *)elem;             //头插法
    new_elem->next = lp->head->next;
    lp->head->next = new_elem;
    ++lp->size;
}

void print_list(const list_type list)
{
    if(list.size != 0){
        node_type *tmp = list.head->next;
        while(tmp != NULL){
            printf("%d ", *(int *)tmp->data);
            tmp = tmp->next;
        }
    }
}

void reverse_list(list_ptr lp)
{
    assert(lp->size != 0);

    node_ptr first = lp->head->next;
    node_ptr second = first->next;
    lp->head->next = NULL;
    while(first != NULL){               //其实相当于把链表元素从前向后再次来了一个头插法
        second = first->next;
        first->next = lp->head->next;
        lp->head->next = first;
        first = second;
    }
}

void destroy_list(list_ptr lp)          //链表析构函数
{
    node_ptr first = lp->head;
    node_ptr second = first->next;
    while(first != NULL){
        second = first->next;
        lp->destroy(first);
        first = second;
    }
}

#endif
二:测试文件
#include "list.h"

#define N 10

void destroy(void *elem)
{
    free(elem);
}

int main()
{
    int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    list_type list;
    
    init_list(&list, destroy);
    
    for(int i=0; i<10; ++i)
        insert_list(&list, array+i);

    print_list(list);
    printf("\n");

    reverse_list(&list);
    print_list(list);
    printf("\n");
    
    destroy_list(&list);

    return 0;
}
三:输出结果
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值