双链表
.h
#include<stdio.h>
#include<stdlib.h>
typedef struct Listnode
{
int num;
struct Listnode* next;
struct Listnode* prev;//往前指
}L;
//只有初始化需要二级指针
//void Init(L** phead);//初始化时,要自己指向自己
//初始化不用二级指针用返回的方法,测试里接收
L*Init();
//打印
void Print(L*phead);
//头插入
void toucha(L*phead,int x);
//头插,尾差可以直接写在poscha,传(phead->next)
//在pos位置之前插入
void poscha(L* pos, int x);
//尾插和头插都可以用在pos里
//尾删
void weishan(L* phead);
//头删
void toushan(L* phead);
//在pos位置删除
void posshan(L* pos);
//查找
L*chazhao(L* phead, int x);
.c
L*my_malloc(int x)//创建哨兵位
{
L* newnode = (L*)malloc(sizeof(L));
if (newnode == NULL)
{
perror("malloc 错");
}
newnode->num = x;
newnode->next = NULL;
newnode->prev = NULL;
return newnode;
}
//初始化不用二级指针用返回的方法,测试里接收
L*Init()
{
L* phead = my_malloc(0);
phead->next = phead;
phead->prev = phead;
return phead;
}
//打印
void Print(L* phead)
{
printf("<head> ");
L* head = phead;
head = head->next;
while (head!= phead)
{
printf("%d ", head->num);
head = head->next;
}
printf("\n");
}
//头插
void toucha(L* phead, int x)
{
L* newnode = my_malloc(x);
//法1:顺序不可乱
newnode->next = phead->next;
phead->next->prev = newnode;
phead->next = newnode;
newnode->prev = phead;
//法二:记住顺序
//L* p = phead->next;
//phead->next = newnode;
//newnode->prev = phead;
//newnode->next = p;
//p->prev = newnode;
}
//在pos位置之前插入
void poscha(L* pos, int x)
{
L* newnode = my_malloc(x);
L* cur = pos->prev;//记住pos前面的地址,不用再去找
newnode->next = pos;
pos->prev = newnode;
cur->next = newnode;
newnode->prev = cur;
}
//尾删
void weishan(L* phead)
{
if (phead->next==NULL)
{
return;
}
//记住尾1和尾2的地址,把尾2和phead连接起来
L* cur = phead->prev;
L* tail = cur->prev;
phead->prev = tail;
tail->next = phead;
free(cur);
cur = NULL;
}
//头删
void toushan(L* phead)
{
if (phead->next == NULL)
{
return;
}
//先连接后释放
L* tail = phead->next;
L* cur = phead->next->next;
phead->next = cur;
cur->prev = phead;
free(tail);
tail = NULL;
}
//在pos位置删除
void posshan(L* pos)
{
L* cur = pos->next;//pos位置后一个地址
L* tail = pos->prev;//pos位置前一个地址
tail->next = cur;
cur->prev = tail;
free(pos);
pos = NULL;
}
//查找
L*chazhao(L* phead, int x)
{
L* cur = phead->next;
while (cur != phead)
{
if (x == cur->num)
{
return cur;
}
cur = cur->next;
}
return NULL;
}