今天用C实现了一个双向链表,这个链表有排序功能,默认按升序排列,接受的参数可以是数字,也可以是字符串。现在把自己写的代码,分享出来。
头文件:
#define DOUBLE_LINK_H_INCLUDED
//双向链表节点
typedef struct Double_Node
{
struct Double_Node* next;
struct Double_Node* pre;
const void* value;//注意,此处声明为const,是考虑到了字符常量
} node;
//判断链表是否为空
extern bool dlink_is_empty();
//链表的大小
extern int dlink_size();
//比较节点值的大小,仅限于数字和字符串
extern int compare(const void* a,const void* b);
//将"value"插入到链表,成功返回0,否则返回-1
extern int dlink_insert(const void *pval);
//返回链表的第一个元素
extern node* peek();
//取出链表的第一个元素,free操作,在poll方法后,不能忘记,否则,会内存泄漏
extern node* poll();
#endif // DOUBLE_LINK_H_INCLUDED
#include #include #include #include #include #include #include "double_link.h" using namespace std;
//链表头部 static node* head = NULL; static node* tail = NULL; //节点数量 static int count = 0;
/** * 创建节点,成功后返回节点指针 * \param void* value 传入的指针 * \return node* */ static node* createNode(const void* value) { node* n = (node*)malloc(sizeof(node)); if (!n) { cout << "failed in createNode!" << endl; return NULL;