冒泡法实现链表排序

#include "stdafx.h"
#include<list>

struct Node{
	int val;
	struct Node* next;
};

void ListSort_ByBubble(struct Node* head)
{
	if (head == NULL)return ;
	Node *startP = head;
	Node *nextP = head->next;
	while (startP->next != NULL)
	{
		//nextP始终指向startP的下一个位置
		nextP = startP->next;
		while (nextP != NULL)
		{
			//将链表中的数值从小到大排序,只改变链表中结点的数值,无需改变链表的结构
			if (startP->val > nextP->val)
			{
				int temp = startP->val;
				startP->val = nextP->val;
				nextP->val = temp;
			}
			
			nextP = nextP->next;
		}
		startP = startP->next;
	}

}

测试结点:

int _tmain(int argc, _TCHAR* argv[])
{
	//测试节点为list(10) -> list1(8) -> list2(9) -> list3(6) ->NULL
	//测试结果应为:list(6) -> list1(8) -> list2(9) -> list3(10) ->NULL
	Node *list = new Node;
	Node *list1 = new Node;
	Node *list2 = new Node;
	Node *list3 = new Node;
	list->val = 10;
	list->next = list1;
	list1->val = 8;
	list1->next = list2;
	list2->val = 9;
	list2->next = list3;
	list3->val = 6;
	list3->next = NULL;		//最后一个节点的next值为空
	ListSort_ByBubble(list);

	while (list != NULL)
	{
		printf("%d\n", list->val);
		list = list->next;
	}
	return 0;
}
结果:




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值