定义类型
typedef int CLDataType;
typedef struct ListNode
{
CLDataType _data;
struct ListNode* _next;
struct ListNode* _prev;
}ListNode;
typedef struct List
{
ListNode* _head;
}List;
函数声明
void ListInit(List* pcl);
void ListDestory(List* pcl);
void ListPushBack(List* pcl, CLDataType x);
void ListPushFront(List* pcl, CLDataType x);
void ListInsert(ListNode* pos, CLDataType x);
void ListPopBack(List* pcl);
void ListPopFront(List* pcl);
void ListErase(List* pcl, ListNode* pos);
void ListPrint(List* pcl);
int ListSize(List* pcl);
int ListEmpty(List* pcl);
ListNode* FindListNode(List* pcl, CLDataType x);
ListNode* BuyListNode(CLDataType x);
函数实现
ListNode* BuyListNode(CLDataType x)
{
ListNode* cur = (ListNode*)malloc(sizeof(ListNode));
if (cur == NULL)
{
perror("use malloc");
}
cur->_data = x;
cur->_next = NULL;
cur->_prev = NULL;
}
void ListInit(List* pcl)
{
assert(pcl);
ListNode* head = BuyListNode(0);
pcl->_head = head;
pcl->_head->_next = pcl->_head;
pcl->_head->_prev = pcl->_head;
}
void ListDestory(List* pcl)
{
assert(pcl);
ListNode* cur = pcl->_head;
while (cur != pcl->_head)
{
ListNode* tmp = cur->_next;
free(cur);
cur = tmp;
}
free(pcl->_head);
pcl->_head = NULL;
}
void ListPushBack(List* pcl, CLDataType x)
{
assert(pcl);
ListInsert(pcl->_head, x);
}
void ListPushFront(List* pcl, CLDataType x)
{
assert(pcl);
ListInsert(pcl->_head->_next, x);
}
void ListInsert(ListNode* pos, CLDataType x)
{
assert(pos);
ListNode* newnode = BuyListNode(x);
ListNode* prev = pos->_prev;
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = pos;
pos->_prev = newnode;
}
void ListPopBack(List* pcl)
{
assert(pcl);
ListErase(pcl, pcl->_head->_prev);
}
void ListPopFront(List* pcl)
{
assert(pcl);
ListErase(pcl, pcl->_head->_next);
}
void ListErase(List* pcl, ListNode* pos)
{
assert(pos);
assert(pos != pcl->_head);
ListNode* prev = pos->_prev;
ListNode* next = pos->_next;
prev->_next = next;
next->_prev = prev;
free(pos);
pos = NULL;
}
void ListPrint(List* pcl)
{
assert(pcl);
ListNode* cur = pcl->_head->_next;
while (cur != pcl->_head)
{
printf("%d-->", cur->_data);
cur = cur->_next;
}
printf("over\n");
}
int ListSize(List* pcl)
{
assert(pcl);
ListNode* cur = pcl->_head->_next;
int count = 0;
while (cur != pcl->_head)
{
count++;
cur = cur->_next;
}
return count;
}
int ListEmpty(List* pcl)
{
assert(pcl);
return ((pcl->_head->_next == pcl->_head) && (pcl->_head->_prev == pcl->_head)) ? 0 : 1;
}
ListNode* FindListNode(List* pcl, CLDataType x)
{
assert(pcl);
ListNode* cur = pcl->_head->_next;
while (cur != pcl->_head)
{
if (cur->_data == x)
{
return cur;
}
cur = cur->_next;
}
return NULL;
}