正文

在论坛里回复别人关于链表操作的帖子2008-11-29 13:15:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/bioexplore/39602.html

分享到:

#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;

}

博客上支持这种语法高亮所以就把源码放到这里了

阅读(2399) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册