头文件
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct list {
int data;
struct list* next;
struct list* prev;
}SL;
void listinit(SL** phead);
void listpushback(SL** phead, int x);//尾插
void listprintf(SL* phead);
void listpopback(SL** phead);
void listpushfront(SL** head, int x);
void listpopfront(SL** head);
SL* listfindpos(SL** head, int x);//查找某个数,并返回节点
void listerase(SL** pos);//删除某个节点
void listdestroy(SL** phead);//销毁双向链表
主函数
#include"main.h"
void listinit(SL** phead)//初始化双向链表
{
*phead = (SL*)malloc(sizeof(SL));
if (*phead == NULL)
{
return;
}
(*phead)->next = *phead;
(*phead)->prev = *phead;
}
void listpushback(SL** phead, int x)//尾插
{
if (phead == NULL) return;
SL* tail = (*phead)->prev;
SL*newnode= (SL*)malloc(sizeof(SL));
if (newnode == NULL)
{
return;
}
newnode->data = x;
tail->next = newnode;
newnode->prev = tail;
newnode->next =*phead;
(*phead)->prev = newnode;
}
void listprintf(SL* phead)//打印
{
if (phead == NULL) return;
SL* cur = phead->next;
while (cur != phead) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
void listpopback(SL** phead)//尾删
{
assert(*phead);
assert((*phead)->next);
SL* tail = (*phead)->prev;
(*phead)->prev = tail->prev;
tail->prev->next = *phead;
free(tail);
}
void listpushfront(SL** head, int x)//头插
{
assert(*head);
SL* front = (*head)->next;
SL* newnode = (SL*)malloc(sizeof(SL));
newnode->data = x;
(*head)->next = newnode;
newnode->prev = *head;
newnode->next = front;
front->prev = newnode;
}
void listpopfront(SL** head)//头删
{
assert(*head);
assert((*head)->next);
SL* front = (*head)->next;
SL* afterfront = front->next;
(*head)->next = afterfront;
afterfront->prev = *head;
free(front);
}
SL* listfindpos(SL** head, int x)//查找某个数,并返回节点
{
SL* cur = (*head)->next;
while (cur != head)
{
if (cur != head)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
}
return NULL;
}
void listinsert(SL**pos,int x) //在某个节点前插入数据
{
assert(*pos);
SL* posprev = (*pos)->prev;
SL* newnode = (SL*)malloc(sizeof(SL));
if (newnode == NULL)
{
return;
}
posprev->next = newnode;
newnode->prev = posprev;
newnode->next = pos;
}
void listerase(SL** pos)//删除某个节点
{
assert(pos);
SL* prev = (*pos)->prev;
SL* next = (*pos)->next;
prev->next = next;
next->prev = prev;
free(*pos);
*pos = NULL;
}
void listdestroy(SL**phead)//销毁双向链表
{
assert(*phead);
SL* cur =(*phead)->next;
while (cur != *phead)
{
SL* next = cur->next;
free(cur);
cur = next;
}
free(phead);
phead = NULL;
}
测试
#include"main.h"
test1()
{
SL* head;
listinit(&head);
listpushfront(&head, 2);
listpushback(&head, 1);
listpushback(&head, 1);
listpushback(&head, 1);
listpopfront(&head);
listpopback(&head);
listprintf(head);
}
int main() {
test1();
return 0;
}