双向链表
代码 1 :
#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
typedef struct node{
data_t data;
struct node * front;
struct node * next;
}duolist_t;
//创建
duolist_t* create_duolist()
{
duolist_t* list=malloc(sizeof(duolist_t));
list->front=NULL; //头结点指向前方的指针
list->next=malloc(sizeof(duolist_t));//头结点指向后面的指针
list->next->front=list;//尾节点指向前面的指针
list->next->next=NULL;//尾节点指向后面的指针
return list;
}
//判空
int isempty(duolist_t* list)
{
if(list==NULL)
return 0;
return list->next->next==NULL;
}
//增
int insert_duolist(duolist_t* list,data_t data)
{
if(list==NULL)
return -1;
duolist_t* newnode=malloc(sizeof(duolist_t));
newnode->data=data;
newnode->front=list;
newnode->next=list->next;
newnode->front->next=newnode;
newnode->next->front=newnode;
return 0;
}
//删
int delete_duolist(duolist_t* list)
{
if(list==NULL||isempty(list))
return -1;
duolist_t* temp=list->next;
temp->front->next=temp->next;
temp->next->front=temp->front;
free(temp);
return 0;
}
//查 返回谁的地址?
duolist_t* locate_duolist(duolist_t* list,data_t data)
{
if(list==NULL||isempty(list))
return NULL;
while(list->next->next!=NULL)
{
if(list->next->data==data)
return list->next;
list=list->next;
}
return NULL;
}
//改
int change_duolist(duolist_t* list,data_t data)
{
if(list==NULL)
return -1;
list->data=data;
return 0;
}
//打印
int print_duolist(duolist_t* list)
{
if(list==NULL||isempty(list))
return -1;
while(list->next->next!=NULL)
{
printf("%3d ",list->next->data);
list=list->next;
}
printf("\n");
return 0;
}
//逆打印
int reprint_duolist(duolist_t* list)
{
if(list==NULL||isempty(list))
return -1;
while(list->next->next!=NULL)
{
list=list->next;
}
list=list->next;
while(list->front->front!=NULL)
{
printf("%3d ",list->front->data);
list=list->front;
}
printf("\n");
return 0;
}
//长度
int length_duolist(duolist_t* list)
{
if(list==NULL||isempty(list))
return 0;
int sum=0;
while(list->next->next!=NULL)
{
sum++;
list=list->next;
}
return sum;
}
//清空
int clear_duolist(duolist_t* list)
{
if(list==NULL||isempty(list))
return -1;
while(list->next->next!=NULL)//length_duolist(list)
{
delete_duolist(list);
}
return 0;
}
//销毁
int destroy_duolist(duolist_t* list)
{
if(list==NULL)
return -1;
if(!isempty(list))
clear_duolist(list);
free(list->next);
free(list);
return 0;
}
int main(int argc, const char *argv[])
{
duolist_t* list=create_duolist();
int i;
for(i=1;i<=15;i++)
{
insert_duolist(list,i*2);
print_duolist(list);
}
change_duolist(locate_duolist(list,20),250);
print_duolist(list);
insert_duolist(locate_duolist(list,250)->front,20);
print_duolist(list);
delete_duolist(locate_duolist(list,250)->front);
print_duolist(list);
reprint_duolist(list);
printf("length_duolist:%d\n",length_duolist(list));
clear_duolist(list);
printf("length_duolist:%d\n",length_duolist(list));
destroy_duolist(list);
list=NULL;
return 0;
}