1. 程式人生 > >C語言連結串列頭插法,尾插法,排序

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