#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node * next;
struct node * prior;
};
typedef struct node Node;
typedef Node * Link;
//函数功能:释放链表
void Release(Link * head)
{
Link p;
while ((*head)->next != *head)
{
p = (*head)->next;
(*head)->next = p->next;
free(p);
}
p = *head;
*head = NULL;
free(p);
}
//函数功能:创建节点
int Node_creat(Link * new_node)
{
int n = 0;
do
{
*new_node = (Link)malloc(sizeof(Node));
n++;
if (n == 10)
{
return 0;
}
}while(!*new_node);
return -1;
}
//函数功能:创建带表头节点的循环双向链表
void Link_creat(Link * head)
{
if (!Node_creat(head))
{
printf("创建失败!\n");
exit(-1);
}
(*head)->next = *head;
(*head)->prior = *head;
}
//函数功能:插入节点,插入方式:头插
void Link_insert_head(Link head,Link new_node)
{
new_node->next = head->next;
new_node->prior = head;
head->next->prior = new_node;
head->next = new_node;
}
//函数功能:插入节点,插入方式:尾插
void Link_insert_tail(Link head,Link new_node)
{
new_node->next = head;
new_node->prior = head->prior;
head->prior->next = new_node;
head->prior = new_node;
}
//函数功能:删除指定数据的节点
void Link_delete(Link head,int date)
{
Link p;
p = head;
do
{
if (p->num == date)
{
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
return;
}
p = p->next;
}while(p != head);
}
//函数功能:释放链表除表头节点以外的节点
void Link_empty(Link head)
{
Link p;
while (head->next != head)
{
p = head->next;
head->next = p->next;
free(p);
}
}
//函数功能:打印链表的数据
void Link_display(Link head)
{
if (head == NULL)
{
printf("链表已释放\n");
return;
}
if (head->next == head)
{
printf("链表为空\n");
return;
}
Link p;
p = head->next;
while ( p != head)
{
printf("%d\n",p->num);
p = p->next;
}
}
int main()
{
int i;
Link head,new_node;
Link_creat(&head);
for (i = 0; i < 10; i++ )
{
if (!Node_creat(&new_node))
{
Release(&head);
printf("创建失败!\n");
exit(-1);
}
new_node->num = i + 1;
//Link_insert_head(head,new_node);
Link_insert_tail(head,new_node);
}
Link_display(head);
Link_delete(head,10);
Link_display(head);
Link_empty(head);
Link_display(head);
Release(&head);
Link_display(head);
return 0;
}
带表头节点的循环双向链表基本操作
最新推荐文章于 2022-06-28 22:29:03 发布