头文件List.h存放函数声明
#ifndef _LIST_H
#define _LIST_H
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int LTDataType;
typedef struct ListNode{
LTDataType _data;
struct ListNode* _next;
struct ListNode* _prev;
}ListNode;
typedef struct List{
ListNode* _head;
}List;
//初始化函数
void ListInit(List* plist);
//销毁,释放函数
void ListDestroy(List* plist);
//尾插
void ListPushBack(List* plist, LTDataType x);
//尾删
void ListPopBack(List* plist);
//头插
void ListPushFront(List* plist, LTDataType x);
//头删
void ListPopFront(List* plist);
//打印函数
void ListPrint(List* plist);
#endif //_LIST_H
源文件List.c存放函数功能实现
#include "List.h"
//初始化函数
void ListInit(List* plist){
assert(plist);
plist->_head = (ListNode*)malloc(sizeof(ListNode));
memset(&plist->_head->_data, 0, sizeof(LTDataType));
plist->_head->_next = plist->_head->_prev = plist->_head;
}
//销毁,释放函数
void ListDestroy(List* plist){
ListNode* tmp = plist->_head->_next;
while (tmp != plist->_head){
tmp->_next->_prev = tmp->_prev;
tmp->_prev->_next = tmp->_next;
free(tmp);
tmp = plist->_head->_next;
}
free(plist->_head);
plist->_head = NULL;
}
//尾插
void ListPushBack(List* plist, LTDataType x){
ListNode* cur = (ListNode*)malloc(sizeof(ListNode));
cur->_data = x;
plist->_head->_prev->_next = cur;
cur->_prev = plist->_head->_prev;
plist->_head->_prev = cur;
cur->_next = plist->_head;
}
//尾删
void ListPopBack(List* plist){
ListNode* tmp = plist->_head->_prev;
if (tmp != plist->_head){
tmp->_prev->_next = tmp->_next;
tmp->_next->_prev = tmp->_prev;
free(tmp);
}
}
//头插
void ListPushFront(List* plist, LTDataType x){
ListNode* cur = (ListNode*)malloc(sizeof(ListNode));
cur->_data = x;
plist->_head->_next->_prev = cur;
cur->_next = plist->_head->_next;
plist->_head->_next = cur;
cur->_prev = plist->_head;
}
//头删
void ListPopFront(List* plist){
ListNode* tmp = plist->_head->_next;
if (tmp != plist->_head){
tmp->_prev->_next = tmp->_next;
tmp->_next->_prev = tmp->_prev;
free(tmp);
}
}
//打印函数
void ListPrint(List* plist){
ListNode* cur;
printf("head<-->");
for (cur = plist->_head->_next; cur != plist->_head; cur = cur->_next){
printf("%d<-->", cur->_data);
}
printf("<-->head\n");
}
源文件main.c用来测试代码功能
#include "List.h"
int main(){
List list;
ListInit(&list);
ListPushFront(&list, 7);
ListPushFront(&list, 6);
ListPushFront(&list, 5);
ListPushFront(&list, 4);
ListPopBack(&list);
ListPopFront(&list);
ListPrint(&list);
ListDestroy(&list);
system("pause");
return 0;
}