#include<iostream>
using namespace std;
struct Node
{
double content;
Node* next;
Node():content(0.0),next(NULL)
Node(double c,Node* n):content(c),next(n)
};
void clearList(Node* h)//链表内存回收
{
if(h)
{
if(h ->next)
{
Node* nextHead= h ->next;
delete h;
clearList(nextHead);
}
else
{
delete h;
}
}
}
//当lastComparedNode->content<toBeInserted->content时
//调用该函数,递归函数
void insertAfterNode(Node* toBeInserted,Node* lastComparedNode)
{
Node* nowNode=lastComparedNode->next;
if(nowNode)//首先判断其后是否还有节点
{
if(nowNode->content >=toBeInserted->content)
{
toBeInserted->next=nowNode;
lastComparedNode->next=toBeInserted;
}
else
{
insertAfterNode(toBeInserted,nowNode);
}
}
else//如果后面没有节点,直接插入
{
lastComparedNode->next=toBeInserted;
}
}
int main()
{
Node* head=new Node();
double contTmp;
bool failed=false;
cout<<"请输入要排序的数,以-1结束"<<endl;
if(cin>>contTmp && contTmp!=-1)
{
head->content=contTmp;//将读入的数值保存在head中
Node* readInNode=NULL;
while(true)
{
if(cin>>contTmp)
{
if (contTmp==-1)
{
break;
}
readInNode=new Node(contTmp,NULL);
if(head->content>=readInNode->content)
{
readInNode->next=head;
head=readInNode;
}
else
{
insertAfterNode(readInNode,head);
}
}
else
{
failed=true;
clearList(head);
cout<<"Failed while reading inputStream!"<<endl;
break;
}
}
}
else
{
failed=true;
cout<<"Failed while reading head Node!"<<endl;
delete head;//释放内存
}
if(!failed)
{
Node* tmpNode=NULL;
cout<<"依次排序为:"<<endl;
int count=0;
for(tmpNode=head;tmpNode!=NULL;tmpNode=tmpNode->next)
{
cout<<tmpNode->content<<'\t';
count++;
if(count%6==0) cout<<endl;
}
clearList(head);
}
system("PAUSE");
return 0;
}
博客上支持这种语法高亮所以就把源码放到这里了
评论