C语言 带有头结点的循环单链表的实现和相关操作。
#include<stdio.h>
#include<stdlib.h>
typedef int DAT;
typedef struct node
{
DAT data;
struct node *next;
}Node;
typedef struct
{
Node *head;
unsigned size;
}list;
void init_list(list *pL)
{
pL->head=NULL;
pL->size=0;
}
Node* mack_node(DAT data)
{
Node *newnode=(Node*)malloc(sizeof(Node));
if(newnode==NULL)
{
printf("内存分配失败");
return;
}
newnode->data=data;
newnode->next=NULL;
return newnode;
}
void push_back_list(list *pL,DAT data)
{
Node *newnode=mack_node(data);
if(pL->head==NULL)
{
pL->head=newnode;
newnode->next=pL->head;
pL->size++;
return;
}
Node *cur=pL->head;
while(cur->next!=pL->head)
{
cur=cur->next;
}
cur->next=newnode;
newnode->next=pL->head;
pL->size++;
}
void push_front_list(list *pL,DAT data)
{
Node *newnode=mack_node(data);
if(pL->head==NULL)
{
pL->head=newnode;
newnode->next=pL->head;
pL->size++;
return;
}
Node *cur=pL->head;
while(cur)
{
if(cur->next==pL->head)
break;
cur=cur->next;
}
cur->next=newnode;
newnode->next=pL->head;
pL->head=newnode;
pL->size++;
}
void pop_front_list(list *pL)
{
if(pL->head==NULL)
{
printf("空链表,删除失败。");
return;
}
Node *chr=pL->head ;
Node *pre=pL->head ;
if(chr->next==pL->head )
{
pL->head =NULL;
free(chr);
chr=NULL;
pL->size--;
return;
}
while(chr)
{
if(chr->next==pL->head )
break;
chr=chr->next;
}
chr->next=pL->head ->next;
pL->head =pL->head ->next;
free(pre);
pre=NULL;
pL->size--;
}
void pop_back_list(list *pL)
{
if(pL->head ==NULL)
{
printf("空链表,删除失败。");
return;
}
Node *chr=pL->head;
Node *pre=NULL;
if(chr->next==pL->head )
{
pL->head =NULL;
free(chr);
chr=NULL;
pL->size--;
return;
}
while(chr->next!=pL->head )
{
pre=chr;
chr=chr->next;
}
pre->next=pL->head ;
free(chr);
chr=NULL;
pL->size--;
}
void destory_list(list *pL)
{
if(pL->head ==NULL)
return;
Node *chr=pL->head ;
Node *pre=NULL;
while(chr->next!=pL->head )
{
pre=chr;
chr=chr->next;
free(pre);
pre=NULL;
}
free(chr);
pL->head =NULL;
chr=NULL;
pL->size =0;
}
void print_list(list *pL)
{
if(pL->head==NULL)
{
printf("空链表\n");
return;
}
Node *cur=pL->head;
while(cur)
{
printf("%d->",cur->data);
cur=cur->next;
if(cur==pL->head)
{
printf(" %d个节点\n",pL->size);
return;
}
}
}
int main ()
{
list List;
init_list(&List);
print_list(&List);
push_back_list(&List,1);
print_list(&List);
push_back_list(&List,12);
print_list(&List);
push_back_list(&List,123);
print_list(&List);
push_front_list(&List,4);
print_list(&List);
push_front_list(&List,45);
print_list(&List);
push_front_list(&List,456);
print_list(&List);
pop_front_list(&List);
print_list(&List);
pop_back_list(&List);
print_list(&List);
destory_list(&List);
print_list(&List);
return 0;
}