1. 程式人生 > >1052:C語言程式設計教程(第三版)課後習題11.8

1052:C語言程式設計教程(第三版)課後習題11.8

1052: C語言程式設計教程(第三版)課後習題11.8

Description

已有a、b兩個連結串列,每個連結串列中的結點包括學好、成績。要求把兩個連結串列合併,按學號升序排列。

Input

第一行,a、b兩個連結串列元素的數量N、M,用空格隔開。 接下來N行是a的資料 然後M行是b的資料 每行資料由學號和成績兩部分組成

Output

按照學號升序排列的資料

Sample Input

2 3
5 100
6 89
3 82
4 95
2 10

Sample Output

2 10
3 82
4 95
5 100
6 89

———-程式碼塊

#include<iostream>
#include<cstdlib>

using namespace std;

typedef struct stu
{
    int xh;
    int score;
    struct stu *next;
}stu;

int main()
{
    int N,M;
    cin>>N>>M;
    stu *head,*a,*b;
    head=(stu*)malloc(sizeof(stu));
    head->next=NULL;

    for(int i=0
;i<N;i++) { a=(stu*)malloc(sizeof(stu)); cin>>a->xh>>a->score; a->next=head->next; head->next=a; } for(int i=0;i<M;i++) { b=(stu*)malloc(sizeof(stu)); cin>>b->xh>>b->score; b->next=head->next; head->next=b; } stu *q,*p; head=head->next; for
(p=head;p;p=p->next) for(q=p;q;q=q->next) if(p->xh>q->xh) { int temp=p->xh; p->xh=q->xh; q->xh=temp; temp=p->score; p->score=q->score; q->score=temp; } while(head) { cout<<head->xh<<' '<<head->score<<endl; head=head->next; } free(head); }