/*
*不带头的链表
**/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int var;
struct node* prev;
struct node* next;
};
//头插法
void Add(int v,struct node**head){
struct node*pnew=(struct node*)malloc(sizeof(struct node));
pnew->var=v;
//如果链表头为空
if (!(*head))
{
//新结点就是头
(*head) = pnew;
pnew->prev=pnew->next=NULL;
}
else
{
//新结点的前驱指针置空
pnew->prev=NULL;
//新结点的后继指针指向链表头
pnew->next=(*head);
//链表头的前驱指针指向新结点
(*head)->prev=pnew;
//链表头指针指向新结点
(*head)=pnew;
}
}
//删除值为v的链表结点
void Del(int v,struct node**head){
if (!head)
{
return;
}
struct node*p=*head,*p1=*head;
while (p)
{
if (p->var == v)
{
if (p == *head)
{
(*head)=p->next;
(*head)->prev=NULL;
//free(p);
printf("已删除(头)\n");
return;
}
else
{
//printf("%d %d\n",p1->var,p->var);
p1->next=p->next;
if (p->next)
{
p->next->prev=p1;
printf("不是最后\n");
}
//free(p);
//printf("%d %d\n",p1->var,p->var);
printf("已删除\n");
return;
}
}
p1=p;
p=p->next;
}
printf("不存在\n");
}
//从头打印链表
void Print1(struct node*head){
struct node*p=head;
while (p)
{
printf("%d ",p->var);
p=p->next;
}
printf("\n");
}
//从尾打印
void Print2(struct node*head){
struct node*p=head;
while (p->next)
p=p->next;
while (p)
{
printf("%d ",p->var);
p=p->prev;
}
printf("\n");
}
int main(){
int a[]={1,2,3,4,5};
int i;
struct node*head=NULL;
for (i=0;i<5;i++)
{
Add(a[i],&head);
}
Print1(head);
Print2(head);
Del(5,&head);
Print1(head);
Del(1,&head);
Print1(head);
Del(3,&head);
Print1(head);
getchar() ;
}
宏定义法,非常巧妙
参考GitHub王博靖
#include <stdio.h>
#include <stdlib.h>
struct node
{
int var;
struct node* prev;
struct node* next;
node(int v):var(v),prev(NULL),next(NULL){}
};
#define LL_ADD(item, list) do { \
item->prev = NULL; \
item->next = list; \
list = item; \
} while(0)
#define LL_REMOVE(item, list) do { \
if (item->prev != NULL) item->prev->next = item->next; \
if (item->next != NULL) item->next->prev = item->prev; \
if (list == item) list = item->next; \
item->prev = item->next = NULL; \
} while(0)
//从头打印链表
void Print1(struct node*head){
struct node*p=head;
while (p)
{
printf("%d ",p->var);
p=p->next;
}
printf("\n");
}
int main(){
node*list=NULL;
int a[]={1,2,3,4,5};
for (int i=0;i<5;i++){
node*p=new node(a[i]);
LL_ADD(p,list);
}
Print1(list);
getchar();
}