C语言 不带头结点的双链表的实现和相关操作。
#include<stdio.h>
#include<stdlib.h>
typedef int DAT;
typedef struct node
{
struct node *prior;
DAT data;
struct node *next;
}Node;
void init_list(Node **pL)
{
(*pL)=NULL;
}
Node* mack_node(DAT data)
{
Node *newnode=(Node*)malloc(sizeof(Node));
if(newnode==NULL)
{
printf("内存分配失败");
return;
}
newnode->prior =NULL;
newnode->data =data;
newnode->next =NULL;
return newnode;
}
void push_back_list(Node **pL,DAT data)
{
Node *newnode=mack_node(data);
if((*pL)==NULL)
{
(*pL)=newnode;
return;
}
Node *cur=(*pL);
while(cur->next)
{
cur=cur->next;
}
cur->next=newnode;
newnode->prior=cur;
}
void push_front_list(Node **pL,DAT data)
{
Node *newnode=mack_node(data);
if((*pL)==NULL)
{
(*pL)=newnode;
return;
}
newnode->next=(*pL);
(*pL)->prior=newnode;
(*pL)=newnode;
}
void pop_front_list(Node **pL)
{
if((*pL)==NULL)
{
printf("链表为空,删除失败。");
return;
}
Node *cur=(*pL);
if(cur->next==NULL)
{
free(cur);
(*pL)=NULL;
cur=NULL;
return;
}
(*pL)=cur->next;
(*pL)->prior=NULL;
free(cur);
cur=NULL;
}
void pop_back_list(Node **pL)
{
if((*pL)==NULL)
{
printf("链表为空,删除失败。");
return;
}
Node *cur=(*pL);
Node *pre=NULL;
if(cur->next==NULL)
{
free(cur);
(*pL)=NULL;
cur=NULL;
return;
}
while(cur->next)
{
pre=cur;
cur=cur->next;
}
free(cur);
pre->next=NULL;
cur=NULL;
}
void destroy_list(Node **pL)
{
if((*pL)==NULL)
return;
Node *cur=(*pL);
Node *pre=NULL;
while(cur)
{
pre=cur;
free(pre);
pre=NULL;
cur=cur->next;
}
(*pL)=NULL;
}
void print_list(Node *pL)
{
if(pL==NULL)
{
printf("空链表\n");
return;
}
Node *cur=pL;
printf("NULL");
while(cur)
{
printf("<- %d -> ",cur->data);
cur=cur->next;
}
printf("NULL\n");
}
int main()
{
Node *first;
init_list(&first);
print_list(first);
push_back_list(&first,1);
print_list(first);
push_back_list(&first,12);
print_list(first);
push_back_list(&first,123);
print_list(first);
push_front_list(&first,4);
print_list(first);
push_front_list(&first,45);
print_list(first);
push_front_list(&first,456);
print_list(first);
pop_front_list(&first);
print_list(first);
pop_back_list(&first);
print_list(first);
destroy_list(&first);
print_list(first);
return 0;
}