DLinkList.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int ElemType;
typedef struct ListNode{
struct ListNode* prev;
struct ListNode* next;
ElemType data;
}ListNode;
ListNode* ListInit();
void ListPrint(ListNode* phead);
void ListDestory(ListNode* phead);
void ListPushBack(ListNode* phead, ElemType x);
void ListPushFront(ListNode* phead, ElemType x);
void ListPopBack(ListNode* phead);
void ListPopFront(ListNode* phead);
ListNode* ListFind(ListNode* phead, ElemType x);
void ListInsert(ListNode* pos, ElemType x);
void ListErase(ListNode* pos);
DLinkList.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "DList.h"
ListNode* BuyListNode(ElemType x)
{
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->data = x;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
ListNode* ListInit()
{
ListNode* phead = BuyListNode(0);
phead->next = phead;
phead->prev = phead;
return phead;
}
void ListPrint(ListNode* phead)
{
assert(phead);
ListNode* cur = phead->next;
while (cur != phead)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
void ListDestory(ListNode* phead)
{
assert(phead);
ListNode* cur = phead->next;
while (cur != phead)
{
ListNode* next = cur->next;
free(cur);
cur = next;
}
free(phead);
phead = NULL;
}
void ListPushBack(ListNode* phead, ElemType x)
{
assert(phead);
ListInsert(phead, x);
}
void ListPushFront(ListNode* phead, ElemType x)
{
assert(phead);
ListInsert(phead->next, x);
}
void ListPopFront(ListNode* phead)
{
ListErase(phead->next);
}
void ListPopBack(ListNode* phead)
{
ListErase(phead->prev);
}
ListNode* ListFind(ListNode* phead, ElemType x)
{
assert(phead);
ListNode* cur = phead->next;
while (cur != phead)
{
if (cur->data == x)
return cur;
cur = cur->next;
}
return NULL;
}
void ListInsert(ListNode* pos, ElemType x)
{
assert(pos);
ListNode* prev = pos->prev;
ListNode* newNode = BuyListNode(x);
prev->next = newNode;
newNode->prev = prev;
newNode->next = pos;
pos->prev = newNode;
}
void ListErase(ListNode* pos)
{
ListNode* prev = pos->prev;
ListNode* next = pos->next;
prev->next = next;
next->prev = prev;
free(pos);
pos = NULL;
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "DList.h"
void testList1()
{
ListNode* plist = ListInit();
ListPushBack(plist, 1);
ListPushBack(plist, 2);
ListPushBack(plist, 3);
ListPushBack(plist, 4);
ListPrint(plist);
ListPushFront(plist, 0);
ListPushFront(plist, -1);
ListPrint(plist);
ListPopFront(plist);
ListPrint(plist);
ListPopBack(plist);
ListPrint(plist);
ListDestory(plist);
}
void testList2()
{
ListNode* plist = ListInit();
ListPushBack(plist, 1);
ListPushBack(plist, 2);
ListPushBack(plist, 3);
ListPushBack(plist, 4);
ListPrint(plist);
ListNode* pos = ListFind(plist, 2);
if (pos)
{
pos->data *= 10;
printf("找到了,并且乘10\n");
}
else
printf("没有找到\n");
ListPrint(plist);
ListInsert(pos, 300);
ListPrint(plist);
ListErase(pos);
ListPrint(plist);
}
int main()
{
testList1();
return 0;
}