本文章采用泛型算法实现了单链表的建立与逆置。代码如下:
一:头文件
#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;
}
三:输出结果