【C语言】合并,排序两个链表

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef struct stu{
    int id;        //学号
    char sex[10];  //性别
    float score;   //成绩
    struct stu *next;  //下一节点的头指针
} STU;

STU *create(){
    STU *p1,*p2,*head;
    int n=0;
    p1 = p2 = (STU*)malloc(sizeof(STU));
    scanf("%d,%f,%s",&p1->id,&p1->score,&p1->sex);
    head = NULL;
    while(p1->id != 0){
        n++;
        if(n == 1)
            head = p1;  //把第一个节点指针赋值给头指针
        else
            p2->next = p1;  //如果是第2.....n个节点  把新分配的p1地址赋值给当前节点的下一个指针元素
        p2 = p1;  //当前节点指针同步到新的分配内存地址
        p1 = (STU*)malloc(sizeof(STU));  //分配新的内存空间
        scanf("%d,%f,%s",&p1->id,&p1->score,&p1->sex);
    }
    p2->next = NULL; //跳出循环后当前节点的下一头指针值为NULL
    return head;
}


/**
 * 移动指针操作
 */
void MoveNode(STU** destRef, STU** sourceRef)
{
    /* the front source node */
    STU* newNode = *sourceRef;
    assert(newNode != NULL);

    /*Advance the source pointer */
    *sourceRef = newNode->next;

    /* Link th eold dest off the new node */
    newNode->next = *destRef;

    /*Move dest to point to the new node */
    *destRef = newNode;
}



STU* SortedMerge(STU* a, STU* b)
{
    STU* result = NULL;

    /*point to the last result pointer */
    STU** lastPtrRef = &result;

    while(1)
    {
        if(a == NULL)
        {
            *lastPtrRef = b;
            break;
        }
        else if(b == NULL)
        {
            *lastPtrRef = a;
            break;
        }
        if(a->id <= b->id)
        {
            MoveNode(lastPtrRef, &a);
        }
        else
        {
            MoveNode(lastPtrRef, &b);
        }
        /*tricky:advance to point to the next ".next" field */
        lastPtrRef = &((*lastPtrRef)->next);
    }
    return (result);
}


int main() {
    STU *p,*psed,*new,*po,*pl;
    p = create();   //新建一个链表
    psed = create();  //新建第二个链表
    po = p;
    pl = psed;
    printf("第一个链表:\n");
    while(1){
        printf("%d\t%s\t%0.2f\n",p->id,p->sex,p->score);
        p=p->next;
        if(p == NULL)
            break;
    }
    printf("第二个链表:\n");
    while(1){
        printf("%d\t%s\t%0.2f\n",psed->id,psed->sex,psed->score);
        psed=psed->next;
        if(psed == NULL)
            break;
    }
    printf("\n");
    new = SortedMerge(po,pl);
    printf("合并的链表:\n");
    while(1){
        printf("%d\t%s\t%0.2f\n",new->id,new->sex,new->score);
        new=new->next;
        if(new == NULL)
            break;
    }
    return EXIT_SUCCESS;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深入沟通_it6688668

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值