C语言-双向循环链表
程序员文章站
2024-03-22 11:29:13
...
先基本实现创建、反转、打印,增删改查之后实现
#include <stdio.h>
#include <stdlib.h>
struct Text
{
int data;
struct Text *next,*prev;
};
struct Text* creatList()
{
struct Text* h =(struct Text*) malloc(sizeof(struct Text));
h->prev = h;
h->next = h;
h->data = 0;
return h;
}
struct Text* tailInsert(struct Text *head,int newdata)
{
struct Text *p = head;
struct Text* new =(struct Text*) malloc(sizeof(struct Text));
while(p->next != head){
p = p->next;
}
new->data = newdata;
p->next = new;
new->prev = p;
new->next = head;
return head;
}
struct Text* headInsert(struct Text *head,int newdata)
{
struct Text *p = head;
struct Text *end = head;
while(end->next != head){
end = end->next;
}
struct Text* new =(struct Text*) malloc(sizeof(struct Text));
new->data = newdata;
new->prev = head;
new->next = p->next;
p->next->prev = new;
p->next = new;
p->prev = end;
return head;
}
void Myprintf(struct Text* head)
{
struct Text *p = head->next;
while(p != head){
printf("%d ",p->data);
p = p->next;
}
putchar('\n');
}
//反向输出
void MyReveprintf(struct Text* head)
{
struct Text *p = head->next;
while(p->next != head){
p = p->next;
}
while(p != head){
printf("%d ",p->data);
p = p->prev;
}
putchar('\n');
}
//双向循环链表反转
struct Text* revertList(struct Text *head)
{
struct Text *tmp = NULL;
struct Text *p = head;
do{
tmp = p->prev;
p->prev = p->next;
p->next = tmp;
p = p->prev;
}while(p != head);
return head;
}
int main()
{
struct Text *head = NULL;
head = creatList();
/*
head = tailInsert(head,1);
head = tailInsert(head,2);
head = tailInsert(head,3);
head = tailInsert(head,4);
head = tailInsert(head,5);
Myprintf(head);
*/
head = headInsert(head,1);
head = headInsert(head,2);
head = headInsert(head,3);
head = headInsert(head,4);
head = headInsert(head,5);
Myprintf(head);
head = revertList(head);
Myprintf(head);
return 0;
}
上一篇: java 两个有序链表合并为一个有序链表
下一篇: 【C语言】双向循环链表