用C++创建一个单向链表,并进行冒泡排序,代码如下:
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
Node *creat() //创建一个单向链表
{
int count = 0;
Node *head, *p1, *p2;
p1 = new Node;
p2 = new Node;
cin >> p1->data;
head = NULL;
while (p1->data != 0) //约定当输入数据为0时,创建链表结束
{
count++;
if (count == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = new Node;
cin >> p1->data;
}
p2->next = NULL;
return head;
}
void Bubblesort(Node *h) //冒泡排序
{
int temp;
Node *endNode = NULL; //endNode指向每次冒泡排序的最后一个节点
Node *pi;
while (endNode != h->next)
{
for (pi = h; pi->next != endNode; pi = pi->next)
{
Node *pj = pi->next;
if (pi->data > pj->data)
{
temp = pi->data;
pi->data = pj->data;
pj->data = temp;
}
}
endNode = pi;
}
}
void show(Node *node) //显示链表
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
int main()
{
cout << "输入数字:";
Node *node = creat();
cout << "排序前链表:";
show(node);
Bubblesort(node);
cout << "排序后链表:";
show(node);
cin.get();
cin.get();
return 0;
}
程序运行结果: