创建链表的同时自动完成结点数据排序

/*
 创建链表时自动完成链表上结点按某一关键字排序
 最简单的方法是在创建链表时用插入结点的方式完成链表的建立

/* C++代码 */

#include <iostream>
using namespace std;

struct  node  //结点结构   
{ int data ;   
  node * next;   
};   

int main()
{
  node * CreateList( );  //建立链表函数声明   
  void  PrintList( node *); //输出链表中结点信息函数声明   
  node * InsertNode(node *,node *); //在链表中插入结点函数声明  
  node * deleteAll(node *);//删除整个链表  
  int linkLength(node * head); //获取链表中结点个数
  node * head=NULL;
  cout<<"开始创建链表,请输入结点数据,当输入数据为0时,建立链表完毕"<<endl;
    /*创建链表*/    
  head=CreateList( ); //调用链表创建函数,返回所建链表的头指针   
    /*遍历输出链表*/  
  PrintList(head);  //调用链表遍历函数,输出全部结点信息   
    /*删除整个链表*/  
  cout<<"
链表上结点个数为:"<<linkLength(head)<<endl;
  head=deleteAll(head);
  cout<<"删除整个链表后,链表上的结点个数为:"<<linkLength(head)<<endl;

    return 0;

}

node * CreateList( ) //建立链表函数声明,通过插入结点来建立链表 
{  node * InsertNode(node *,node *); //在链表中插入结点函数声明
   node *head=NULL;
   node *s;
   s=new node;
   cin>>s->data;
   s->next=NULL;
   while(s->data!=0)
   {
      head=InsertNode(head,s);
      s=new node;
      cin>>s->data;
      s->next=NULL;
   }
   return head;
}

node * InsertNode(node *head,node * s)  //插入结点的函数,head为链表头指针,s指向要插入的新结点   
{node *p,*q;                           
 p=head;   //使p指向链表中的第一个结点         
 if(head==NULL)      //原来的链表是空表   
 { head=s;           //使head指向的新结点作为头结点   
   s->next=NULL;       
 }            
 else  //原来的链表不是空表   
 {while((s->data>p->data) && (p->next!=NULL)) //用循环定位要插入的结点位置p,使s插入到p之前的位置   
    {q=p;  //q记录下当前的p,即q指向p的前一个结点   
     p=p->next;   //p后移一个结点   
    }      
  if(s->data<=p->data)  //要插入的结点数据比最后一个结点数据小   
  {   if(head==p)  //判断是否插入链表中的第一个结点之前   
      { head=s;  //插到原来第一个结点之前         
         s->next=p;  
     }      
      else  //插到q指向的结点之后,p指向的结点之前   
      { q->next=s;  
        s->next=p;           
      }         
  }   
  else   //要插入的结点数据比最后一个结点数据还大   
  {  p->next=s;    // 插到链表最后的结点之后,作为链表的尾结点   
     s->next=NULL;  
  }   
 }       
   cout<<"成功完成一个新结点插入..."<<endl;  
   return (head);  
}  

void  PrintList( node * head)  //输出链表中结点信息函数,链表遍历   
{    node *p=head;  
     int i=1;  
     cout<<endl<<"遍历链表..."<<endl;  
    if (head!=NULL)  //如果链表非空,即链表中有结点   
        do             //循环输出接点数据,直到移动到链表尾,即最后一个结点   
        {     cout<<""<<i++<<"个结点数据为:"<<p->data<<endl;   
               p=p->next;                  
        }while(p!=NULL) ;  
    else  
    {  
      cout<<"链表是空链表!"<<endl;  
    }  
}  

node * deleteAll(node *head)//删除整个链表
{
   if(head!=NULL)
   {
      node *p,*q;
      p=head;
      q=head;
      do
      {p=p->next;
       head=p;
       delete q;
       q=p;  
      }while(p!=NULL);
      head=NULL;
   }
     return head;
}


 int linkLength(node * head) //获取链表中结点个数
 {
    int n=0;
    node *p;
    if(head==NULL)
        return 0;
    else
    { p=head;
      while(p!=NULL)
      {
        n++;
        p=p->next;
      }
      return n;        
    } 
 }

原文地址:https://www.cnblogs.com/beautiful-code/p/5239401.html