最近給自己正在做的項目寫了一個連結清單代碼, 主要用于PRO*C的select資料查詢結果的存儲. 發到上面來分享一下, 代碼很短.
db_list.h:
#ifndef DB_LIST_H
#define DB_LIST_H
typedef struct db_list_node
{
void *data;
struct db_list_node *next;
struct db_list_node *prev;
}db_node;
typedef struct db_list
{
db_node * head;
db_node * cur;
}db_list;
db_list * init_db_list();
db_node *add_to_list(void *data, db_list * list);
void clear_db_list(db_list * list);
#endif
db_list.c:
#include <stdlib.h>
#include "db_list.h"
db_list * init_db_list()
{
db_list *l = (db_list *)malloc(sizeof (db_list));
l->head = NULL;
l->cur = NULL;
l ->head = (db_node *)malloc(sizeof (db_node));
l->head->data = NULL;
l->head->prev = NULL;
l->head->next = NULL;
l ->cur = l-> head;
return l;
}
db_node *add_to_list(void *data, db_list * list)
{
db_node *n = NULL;
if (list == NULL)
return NULL;
if (data == NULL)
return NULL;
n = (db_node *)malloc(sizeof (db_node));
n->data = data;
n->prev = NULL;
n->next = NULL;
list ->cur->next = n;
n->prev = list-> cur;
list->cur = list->cur-> next;
return list-> cur;
}
void clear_db_list(db_list * list)
{
while (list->cur != NULL && list->cur != list-> head)
{
list ->cur = list->cur-> prev;
free(list->cur-> next);
}
free(list -> head);
list->head = NULL;
list->cur = NULL;
free(list);
list = NULL;
}
這是main.c檔案, 拿幾個int型簡單的測試了一下, 附帶一個簡單的print函數, 這個可根據需要簡單修改. 沒有加到資料結構的标準函數中.
#include <stdio.h>
#include "db_list.h"
static void print_list(db_list * list)
{
db_node *i = NULL;
for (i = list->head->next; i != NULL; i = i-> next)
printf("0x%d ", *(int *)(i-> data));
}
int main()
{
int a = 1000 ;
int b = 2000 ;
int c = 3000 ;
int d = 4000 ;
db_list *list = init_db_list();
insert_to_list(& a, list);
insert_to_list(& b, list);
insert_to_list(& c, list);
insert_to_list(& d, list);
print_list(list);
clear_db_list(list);
return 0 ;
}
Makefile檔案如下:
OBJ = main.o db_list.o
EXE = test
CC = gcc
$(EXE): $(OBJ)
$(CC) -o [email protected] $^
main.o: main.c db_list.h
$(CC) -c -g $<
db_list.o: db_list.c db_list.h
$(CC) -c -g $<
clean:
rm - rf test
rm -rf *.o