C語言鏈表頭插法,尾插法,排序


題目描述

火車站要組裝一列動車。每列車廂有車廂編號、座位數和座位等級。現在請你把它們組裝起來,要求按照車廂號碼升序排列,並輸出每列車廂的信息。請使用鏈表來實現。

輸入

輸入有多組。

每組有多行。第一行是個正整數n,表示車廂數目。接下來有n行數據,每行數據有3個值,分別是車廂編號、座位數和座位等級。

輸出

輸出該動車每列車廂的信息。安裝后輸入先輸出的方式輸出。

樣例輸入

3
1 108 二等座
3 108 二等座
2 54 一等座
3
2 54 一等座
1 108 二等座
3 108 二等座

樣例輸出

車廂號:1,座位數:108,二等座
車廂號:2,座位數:54,一等座
車廂號:3,座位數:108,二等座
該列車共有270個座位
車廂號:1,座位數:108,二等座
車廂號:2,座位數:54,一等座
車廂號:3,座位數:108,二等座
該列車共有270個座位

 

#include<stdio.h>

#include<stdlib.h>

struct train{

    int no;

    int seat;

    char level[9];

};

struct node{

      struct train data;

      struct node *next;

};

//將結點q插入在以head為頭指針的鏈表的頭部

struct node *insert_head(struct node *head ,struct node *q)

{

        if(q != NULL)

        {

              q->next = head;

              head = q;

        }

     return head;

}

 //將結點q插入在以head為頭指針的鏈表的尾部

struct node *insert_tail(struct node *head ,struct node *q)

        struct node *p = head;

        if(q != NULL)

       {

           while(p&&p->next)

           {

              p = p->next;

 

           }

           if(head == NULL)

           {

              q->next = head;

              head =q;

              p=q;

           }

           else 

           {

                q->next = NULL;

                p->next = q;

                p=p->next;

           }

       }

        

}

 //將新結點q插入在以head為頭指針的鏈表中,並且要升序排列

struct node *insert_order(struct node *head,struct node *q)

{

       struct node *p = head;

       if(head == NULL)

       {

             q ->next =head;

             head =q;

             return head;

       }

       if(p->data.no>q->data.no)

       {

             q->next = head;

             head = q;

             return head;

       }

 //尋找插入位置p(新結點q要插入在p后)

      while(p->next != NULL && p->next->data.no<q->data.no)//若使用降序則p->next->data.no>q->data.no

      {

            p=p->next;

            q->next = p->next;

            p->next = q;

            return head;

      }

}

//歷遍

void print(struct node *head)

{

       struct node *p = head;

       while(p != NULL)

       {

          printf("車廂號:%d,座位號:%d,%s\n",p->data.no,p->data.seat,p->data.level);

          p = p->next;

       }

}

 int main()

{

      int n,s,i;

      struct node *head = NULL;

      struct node *p = NULL;

      struct node *q = NULL;

      

      while(scanf("%d",&n)!=EOF)
      {
             head=NULL;
             s=0;
             for(i=0;i<n;i++)
             {
                     q=(struct node *)malloc(sizeof(struct node));
                     scanf("%d %d %s",&q->data.no,&q->data.seat,q->data.level);
                     q->next=NULL;
                     s+=q->data.seat;
                     head=insert_order(head,q);
             }

 

             print(head);

 

             printf("該列車共有%d個座位\n",s);
      }
          return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM