#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;
}
结果: