Problem:
Solution:
題目要求很清楚,先建立一個鏈表,再對鏈表進行類似於冒泡的排序即可
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct LNode
{
int val;
struct LNode *next;
};
int main()
{
int n,m;
LNode *head,*p,*q;
while (cin >> n)
{
head = (LNode*)malloc(sizeof(LNode));
head -> next = NULL;
q = head;
if (n == 0) cout<<endl;
else
{
for (int i = 0;i < n;i++)
{
cin >> m;
p = (LNode*)malloc(sizeof(LNode));
p -> val = m;
q -> next = p;
q = q -> next;
}
p -> next = NULL;
}
p = head->next;
while(p!=NULL){
q=p->next;
while(q!=NULL){
if(p->val>q->val){
int temp=p->val;
p->val=q->val;
q->val=temp;
}
q=q->next;
}
p=p->next;
}
while (head->next)
{
cout <<head->next->val<< " " ;
head = head->next;
}
}
free(head);
free(p);
free(q);
return 0;
}