双向链表排序

//双向链表排序
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值