刚编的链表程序**晒晒**
程序代码:/*带头结点的双向循环链表相关操作 结点采用尾部插入*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;//后继
struct node *prev;//前驱
};
struct node *temp;
//初始化链表
struct node * init_list(struct node *head)
{
head = (struct node*) malloc (sizeof (struct node));
if (NULL == head)
{
exit(-1);
}
head->next = head;
head->prev = head;
return head;
}
//添加结点
void add(struct node *next, struct node *prev, struct node *position)
{
position->next = next;
prev->next = position;
position->prev = prev;
next->prev = position;
}
//向链表中添加结点
void add_node(struct node *head, struct node *position)
{
add(head->prev->next, head->prev, position);
}
//删除结点 返回被删的上一个结点
struct node * delet(struct node *next, struct node *prev)
{
prev->next = next;
next->prev = prev;
return prev;
}
//从链表中删除某结点 与data数值相同的
void delet_node(struct node *head, int data)
{
struct node *p;
temp = head->next;
while (temp != head)
{
if (temp->data == data)
{
p = delet(temp->next, temp->prev);
free(temp);
temp = p;
}
temp = temp->next;
}
}
//修改链表中的结点 与data数值相同的
void chg_node(struct node *head, int data, int newValue)
{
temp = head->next;
while (temp != head)
{
if (temp->data == data)
{
temp->data = newValue;
}
temp = temp->next;
}
}
//删除整个链表
void delet_list(struct node *head)
{
temp = head->next;
while (temp != head)
{
delet (temp->next, temp->prev);
free(temp);
temp = head->next;
}
free(head);
head = NULL;
printf("删除成功!\n");
}
//先序打印
void prev_print_list(struct node *head)
{
temp = head->next;
while (temp != head)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
//后序打印
void post_print_list(struct node *head)
{
temp = head->prev;
while (temp != head)
{
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}
void function()
{
struct node *head = NULL;
struct node *temp = NULL;
int index = 10;
printf("初始化链表\n");
head = init_list(head);//初始化
printf("先序打印双向循环链表:");
prev_print_list(head);
printf("后序打印双向循环链表:");
post_print_list(head);
printf("\n\n项链表中连续插入 %d 个元素\n", index);
while (index)
{
temp = (struct node*) malloc (sizeof(struct node));
temp->data = index--;
add_node(head, temp);//向链表中添加结点
}
printf("先序打印双向循环链表:");
prev_print_list(head);
printf("后序打印双向循环链表:");
post_print_list(head);
printf("\n\n删除数据为 3 的结点\n");
delet_node(head, 3);
printf("先序打印双向循环链表:");
prev_print_list(head);
printf("后序打印双向循环链表:");
post_print_list(head);
printf("\n\n修改数据为 4 的结点 新值为 18\n");
chg_node(head, 4, 18);
printf("先序打印双向循环链表:");
prev_print_list(head);
printf("后序打印双向循环链表:");
post_print_list(head);
printf("\n\n删除整个链表\n");
delet_list(head);
}
int main(void)
{
function();
return 0;
}









