有序链表的建立

第一种,直接在输入数据的时候找到要插入的合适位置。 

//版本1
#include "iostream"
using namespace std;
struct node
{
	int data;
	struct node *next;
};

int main()
{
	int n;
	cin>>n; //总共有n个数
	struct node *head, *p, *q, *r;
	head = (struct node *)malloc(sizeof(struct node));
	head->next = NULL;

	//相当于找到位置插入新的元素
	for (int i = 0; i<n; i++)
	{
		//新节点r
		r = (struct node *)malloc(sizeof(struct node));
		r->next = NULL;
		cin>>r->data; //依次输入n个数
		//p、q逐次遍历链表
		p = head;
		q = p->next;
		while (q != NULL && r->data>q->data)
		{
			
			q = q->next;
			p = p->next;
		}
		r->next = q;
		p->next = r;
	}

	r = head->next;
	while (r != NULL)
	{
		cout<<r->data;
		if (r->next != NULL)  cout<<" ";
		r = r->next;
	}
	cout<<endl;
	return 0;
}

 第二种,链表建立完了之后再排序,中间过程类似于冒泡排序,类似的还可以写成选择排序。

//版本2
#include "iostream"
using namespace std;

struct node
{
	int data;
	struct node *next;
};

int main()
{
	struct node *head, *tail, *p, *q;
	head = (struct node *)malloc(sizeof(struct node));
	head->next = NULL;
	tail = head;
	int  n; 
	cin >> n;  //总共n个数
	for (int i = 1; i <= n; i++)
	{
		p = (struct node *)malloc(sizeof(struct node));
		p->next = NULL;
		cin >> p->data; //依次输入n个数
		tail->next = p;
		tail = p;
	}
	struct node *r;
	r = head;
	//相当于冒泡排序
	while (r->next != NULL)
	{
		p = head->next;
		q = p->next;
		while (q != NULL)
		{
			if (p->data>q->data)
			{
				int t = p->data;
				p->data = q->data;
				q->data = t;
			}
			else
			{
				p = p->next;
				q = q->next;
			}
		}
		r = r->next;
	}

	r = head->next;
	while (r != NULL)
	{
		cout<< r->data;
		if (r->next != NULL)   cout<<" ";
		r = r->next;
	}
	cout << endl;
	return 0;
}

 

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值