编程菜鸟的日记-初学尝试编程-单链表

//单链表的头插法和尾插法建立,以及直接插入法递增排序

#include <iostream>

#include <string>

#include <stdlib.h>

#define ElemType int

using namespace std;

typedef struct List

{

    ElemType data;

    struct List *next;

 }List;

void CreatListF(List *L,ElemType a[],int n)

{

   List *s;

   L->next=NULL;

   int i;

   for(i=0;i<n;i++)

     {

        s=(List *)malloc(sizeof(struct List));

        s->data=a[i];

        s->next=L->next;

        L->next=s;

       }

}

void CreatListR(List *L, ElemType a[],int n)

{

   List *r,*s;

   L->next=NULL;

   r=L;

   int i;

   for(i=0;i<n;i++)

      {

         s=(List *)malloc(sizeof(struct List));

         s->data=a[i];

         r->next=s;

         r=s;

        }

         r->next=NULL;

}

void SortList(List *L)

{

     List *p=L->next,*q,*r;

     if(p!=NULL)

     {

        r=p->next;

        p->next=NULL;

        p=r;

        while(p!=NULL)

          {

               r=p->next;

               q=L;

               while(q->next!=NULL && q->next->data<p->data)

                {

                     q=q->next;

                 }

               p->next=q->next;

               q->next=p;

               p=r;

           }

      }

}

void Display(List *L)

{

     List *p=L->next;

      while(p!=NULL)

      {

           cout<<p->data<<" ";

            p=p->next;

        }

     cout<<endl;

}

int main()

{

   List *L1,*L2;

   L1=(List *)malloc(sizeof(struct List));

   L2=(List *)malloc(sizeof(struct List));

   ElemType a[10]={7,6,1,4,9,10,5,8,2,3};

   int n=sizeof(a)/sizeof(ElemType);

   CreatListF(L1,a,n);

   Display(L1);

   CreatListR(L2,a,n);

   Display(L2);

   SortList(L1);

   Display(L1);

   SortList(L2);

   Display(L2);

   system("pause");

   return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2013-10-25 15:40  编程的爬行者  阅读(153)  评论(0编辑  收藏  举报