两个链表按升序合并

设已经建立两个链表,且两个链表都是以学号升序排列写的,要求编写一个函数,将两个链表按升序合并。
#include < stdlib.h >
#include
< stdio.h >
#include
< conio.h >
#include
< ctype.h >

#define  LEN sizeof(struct student)

extern  unsigned _floatconvert;     /* 防止floating point formats not linked 错误发生 */
#pragma extref _floatconvert

typedef 
struct  student    
{
    
long  num;
    
float  score;
    
struct  student  * next;
}STU;

STU 
* CreateEnd()
{
    
int  n = 0 ;
    STU 
* p1, * p2, * head;
    head
= NULL;
    p1
= (STU  * )malloc(LEN);         /* 创建第一个结点 */
    scanf(
" %ld,%f " , & p1 -> num, & p1 -> score);
    p1
-> next = NULL;
    
while (p1 -> num != 0 )         /* 将结点加入链表 */
    {
        
++ n;
        
if (n == 1 )         /* 是第一个结点,作表头 */
            head
= p1;
        
else              /* 不是第一个结点,作表尾 */
            p2
-> next = p1;
        p2
= p1;
        p1
= (STU  * )malloc(LEN);     /* 开辟下一个结点 */
        scanf(
" %ld,%f " , & p1 -> num, & p1 -> score);
        p1
-> next = NULL;
    }
    free(p1);            
/* 释放最后一个结点所占的内存 */
    
return  (head);             /* 返回链表的头指针 */
}

void  print(STU  * head)
{
    STU 
* p;
    p
= head;
    
do
    {
        printf(
" %ld\t%5.1f\n " ,p -> num,p -> score);
        p
= p -> next;
    }
while (p != NULL);
}

STU 
* merge(STU  * p1,STU  * p2)
{
    STU 
* p, * head;
    
if (p1 -> num < p2 -> num)
    {
        head
= p = p1;p1 = p1 -> next;}
    
else
    {
        head
= p = p2;p2 = p2 -> next;}
    
while (p1 != NULL  &&  p2 != NULL)
        
if (p1 -> num < p2 -> num)
        {
            p
-> next = p1;
            p
= p1;
            p1
= p1 -> next;
        }
        
else
        {
            p
-> next = p2;
            p
= p2;
            p2
= p2 -> next;
        }
    
if (p1 != NULL)
        p
-> next = p1;
    
else
        p
-> next = p2;
    
return  head;
}

void  main()
{
    STU 
* p1, * p2, * head;
    printf(
" Please input first link information:\n " );
    p1
= CreateEnd();
    print(p1);
    printf(
" \nPlease input second link information:\n " );
    p2
= CreateEnd();
    print(p2);
    printf(
" \nThe merged link is:\n " );
    head
= merge(p1,p2);
    print(head);
    getch();
}

你可能感兴趣的:(链表)