//双向链表排序
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct lint
{
int data;
struct lint *prev;
struct lint *next;
}lint, *plist;
void stamp(plist head);
//闯将头节点
plist LOOC(void)
{
plist head = malloc(sizeof(lint));
if(head == NULL)
{
printf("head erreo\n");
return NULL;
}
head->data = 0;
head->next = NULL;
head->prev = NULL;
return head;
}
//创建新节点
plist Her_a(int data)
{
plist newnode = malloc(sizeof(lint));
if(newnode == NULL)
{
printf("newnode error\n");
return NULL;
}
newnode->data = data;
newnode->prev = NULL;
newnode->next = NULL;
return newnode;
}
//尾部插入
int tail(plist head, int data)
{
plist new = Her_a(data);
plist p = head;
while(p->next != NULL)
{
p = p->next;
}
p->next = new;
new->prev = p;
new->next = NULL;
return 0;
}
//循环尾部插入
void Her_b(plist head)
{
//随机数赋值
srand((unsigned int) time(NULL));
int red = rand()%10 + 10;
for(int i = 0; i <red; i++)
{
int times = rand()%50 + 50;
tail(head, times);
}
stamp(head);
}
//打印
void stamp(plist head)
{
head = head->next;
printf("-head");
while(head->next != NULL)
{
printf("-%d", head->data);
head = head->next;
}
printf("\n");
}
int exchange(plist head, plist p, plist q)
{
//断开节点
// 判断是否为尾节点
if(q->next == NULL)
{
p->next = NULL;
q->prev = NULL;
}
else
{
p->next = q->next;
q->next->prev = p;
q->next = q->prev = NULL;
}
//提出插入比较
p = head;
while(p->next != NULL)
{
if(p->next->data > q->data)
{
q->next = p->next;;
p->next->prev = q;
p->next = q;
q->prev = p;
break;
}
p = p->next;
}
return 0;
}
// 比较
int compare(plist head)
{
plist p = NULL;
while(1)
{
p = head->next;
while(p->next != NULL)
{
// 比较
if(p->data > p->next->data)
{
exchange(head, p, p->next);
break;
}
p = p->next;
}
if(p->next == NULL)
{
break;
}
}
stamp(head);
}
int main(int argc, char const *argv[])
{
plist myhead = LOOC();
Her_b(myhead);
compare(myhead);
return 0;
}
双向链表排序
最新推荐文章于 2023-07-21 15:54:56 发布