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

猜你喜欢

转载自www.cnblogs.com/zy9535/p/10182333.html