6、单链表排序
题目:单链表排序
分析:冒泡排序
//单链表排序
#include<iostream>
using namespace std;
typedef struct node
{
int data;
node *next;
}linklist;
linklist *head=NULL;
//创建链表
linklist* CreateList(int* arr,int len)
{
int data;
linklist* pCur,* pRear;
head=(linklist*)malloc(sizeof(linklist));
pRear=head;
int count=0;
while(count<len)
{
pCur=(linklist*)malloc(sizeof(linklist));
pCur->data=arr[count];
pRear->next=pCur;
pRear=pCur;
count++;
}
pRear->next=NULL;
return head;
}
//显示链表
void ShowList(linklist* p)
{
while(p)
{
cout<<p->data <<' ';
p=p->next;
}
cout << endl;
}
//链表冒泡排序
void BubbleSortList(linklist* p)
{
linklist* pTemp;
linklist* pNode;
for(pTemp=p->next;pTemp->next;pTemp=pTemp->next)
{
for(pNode=p->next;pNode->next;pNode=pNode->next)
{
if(pNode->data > pNode->next->data)
{
swap(pNode->data,pNode->next->data);
}
}
}
}
int main()
{
int a[]={3,4,5,1,2,-1,7};
CreateList(a,sizeof(a)/sizeof(a[0]));
BubbleSortList(head);
ShowList(head->next);
return 0;
}

本文介绍了使用冒泡排序算法对单链表进行排序的方法,包括链表的创建、显示和排序过程。通过实例展示了如何将数组转换为链表,并应用冒泡排序对链表中的元素进行升序排列。
393

被折叠的 条评论
为什么被折叠?



