头文件定义:
#pragma once #include <stdlib.h> #include <stdio.h> #include <functional> using namespace std; //定义链表节点 typedef struct CIRCLE_NODE{ CIRCLE_NODE * next; }Node; //定义链表 typedef struct CIRCLE_LINK_LIST { Node header; int size; //还可以增加尾节点 }CircleList; //定义链表API //比较,返回true就删除,具体由使用者来实现 using Callback = function<bool(Node*, Node*)>; //定义打印输出函数,由使用者来实现 typedef void(*PRINTF_NODE)(Node *); //初始化 CircleList * initLinkList(); //插入指定位置 bool insertNode(CircleList * list,int position, Node * data); //获取头节点 Node * getFrontNode(CircleList * list); //根据位置删除节点 bool removePosition(CircleList * list, int position); //删除数据 bool removeNode(CircleList * list, Node * data, Callback callback); //获取链表的长度 int getSize(CircleList * list); //查找当前节点的位置 int findNodePosition(CircleList * list, Node * data, Callback compare); //打印当前节点信息 void printNodeInfo(Node * data, PRINTF_NODE print); //判断是否为空 bool isEmpty(CircleList * list); //释放 void freeList(CircleList * list);
函数具体实现
#include "CircyleLinkList.h" using namespace std; //初始化双向链表 CircleList * initLinkList() { CircleList * list = new CircleList; list->header.next = &(list->header); list->size = 0; return list; } //插入指定位置 bool insertNode(CircleList * list, int position, Node * data) { if (list==NULL || data ==NULL){ return false; } if (position > list -> size || position < 0) { position = list->size; } Node * current = &(list->header); for (size_t i = 0; i < position; i++){ current = current->next; } //插入当前位置 data->next = current->next; current->next = data; list->size++; return true; } //获取头节点 Node * getFrontNode(CircleList * list) { if (list == NULL) { return NULL; } return list ->header.next; } //根据位置删除节点 bool removePosition(CircleList * list, int position) { if (list == NULL) { return false; } if (position>list->size || position <0){ return false; } Node * current = &(list->header); for (size_t i = 0; i < position; i++){ current = current->next; } //要删除的链表节点 Node * temp = current->next; current->next = temp->next; list->size--; return true; } //删除数据 bool removeNode(CircleList * list, Node * data, Callback callback) { if (list == NULL || data == NULL) { return false; } Node * temp = &(list->header); for (size_t i = 0; i < list->size; i++){ temp = temp->next; if (callback(temp, data)) { removePosition(list, i); break; } } } //获取链表的长度 int getSize(CircleList * list) { return list->size; } //查找当前节点的位置 int findNodePosition(CircleList * list, Node * data,Callback compare) { if (list == NULL || data == NULL || compare==NULL) { return -1; } Node * current = list->header.next; for (size_t i = 0; i < list->size; i++) { current = current->next; if (compare(current,data)) { return i; } } return -1; } //打印当前节点信息 void printNodeInfo(Node * data, PRINTF_NODE print) { print(data); } //判断是否为空 bool isEmpty(CircleList * list) { return list->size == 0; } //释放 void freeList(CircleList * list) { delete &(list->header); }; //获取链表的长度 int getSize(CircleList * list) { return list->size; }