#include <tchar.h>
#include <iostream>
using namespace std;
typedef struct student{
int data;
struct student * next;
} node;
node* create()
{
node *head, *p, *s;
int x, cycle = 1;
head = (node *)malloc(sizeof(node));
p = head;
while(cycle)
{
cout << "please input the data: ";
cin >> x;
cout << endl;
if( x != 0)
{
s = (node *)malloc(sizeof(node));
s->data = x;
p->next = s;
p = s;
}
else
{
cycle = 0;
}
}
p->next = NULL;
head = head->next;
return head;
}
int length(node *head)
{
int n = 0;
node *p;
p = head;
while (p != NULL)
{
p = p->next;
n++;
}
return n;
}
void print(node *head)
{
int n;
node *p;
p = head;
n = length(head);
cout << "There is " << n << " data in list\n" << endl;
while(p != NULL)
{
cout << p->data << " -> ";
p = p->next;
}
cout << endl;
}
node *sort(node *head)
{
node *p;
int n;
n = length(head);
if(head == NULL || head->next == NULL)//排除链表为空或单个节点的情况
return head;
p = head;
for(int j=1; j<n; j++)//采用冒泡排序,每次都把最大的节点放到最后
{
p = head;
for(int i=0; i<n-j; i++)
{
if(p->data > p->next->data)
{
int temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
return head;
}
int _tmain(int argc, _TCHAR * argv[])
{
node *head;
head = create();
print(head);
head = sort(head);
print(head);
return 0;
}
编程实现单链表的排序
最新推荐文章于 2024-09-09 23:42:18 发布