單鏈表排序問題
看一個N諾單鏈表排序的題目,使用尾插法建立鏈表,然後冒泡進行排序
這裏是五個元素進行排序
#include<iostream>
using namespace std;
struct Node
{
int Element;
Node *Next;//節點
};
int main()
{
int temp;
Node *head=new Node;//實例化分配
Node *tail=head;//尾
for(int i=0;i<5;++i)
{
cin>>temp;
Node *a=new Node;
a->Element=temp;
tail->Next=a;
tail=tail->Next;//尾插法建立鏈表
}
Node *p=head->Next;//頭結點
Node *q=p->Next;//q之後的相鄰結點
int n=5;
while(n--)
{
while(q!=NULL)
{
if(p->Element>q->Element)
{
int E_temp=p->Element;
p->Element=q->Element;
q->Element=E_temp;//二者交換
}
p=q;//往後走冒泡排序
q=q->Next;
}
p=head->Next;
q=p->Next;
}
while(p!=NULL)
{
cout<<p->Element<<" ";
p=p->Next;
}
return 0;
}