线性表的插入C语言版

以前写的,比较冗长。

#include <stdio.h>
#include <malloc.h>
//算法2.1 线性表的插入 
struct List{
    int n;
    struct List *next;
};

struct List *create();
struct List *order(struct List *p1,struct List *p2);
void print(struct List *p);

int main(){
    struct List *L1=(struct List*)malloc(sizeof(struct List));
    struct List *L2=(struct List*)malloc(sizeof(struct List));
    struct List *L3=(struct List*)malloc(sizeof(struct List));
    printf("Enter the first array(enter 0 to stop):");
    L1=create();
    printf("\nEnter the second array:");
    L2=create();
    L3=order(L1,L2);
    print(L3);
}

struct List *create()                                                           //有关循环条件的疑问 
{   struct List *temp=(struct List*)malloc(sizeof(struct List));
    struct List *p=(struct List*)malloc(sizeof(struct List));
    struct List *head=(struct List*)malloc(sizeof(struct List));
    head=p;
    scanf("%d",&p->n);
    for(;;)
    {   temp=(struct List*)malloc(sizeof(struct List));
        scanf("%d",&temp->n);
        if(temp->n==0){p->next=NULL;break;}
        p->next=temp;
        p=temp;
    };
                     /*p=NULL与p->next=NULL的不同; NULL是0x00表示指针指向一个无效地址。
                      因为如果指针已分配,肯定是指向一个非0x00的地址。p之前已经分配过了就不能直接再NULL了*/
    return(head);
}

struct List *order(struct List *p1,struct List *p2)
{
    struct List *temp=(struct List*)malloc(sizeof(struct List));
    struct List *p3=(struct List*)malloc(sizeof(struct List));
    struct List *head=(struct List*)malloc(sizeof(struct List));
    head=p3;
    if(p1->n<p2->n)
        p3->n=p1->n,p1=p1->next;
    else
        p3->n=p2->n,p2=p2->next;          //初始化p3 
    while(p1!=NULL&&p2!=NULL){
    temp=(struct List*)malloc(sizeof(struct List));
    if(p1->n < p2->n)
        temp->n=p1->n,p3->next=temp,p3=temp,p1=p1->next;
    else
        temp->n=p2->n,p3->next=temp,p3=temp,p2=p2->next;    
    }

    while(p1!=NULL){
        temp=(struct List*)malloc(sizeof(struct List));
        temp->n=p1->n,p3->next=temp,p3=temp,p1=p1->next;
    }

    while(p2!=NULL){
        temp=(struct List*)malloc(sizeof(struct List));
        temp->n=p2->n,p3->next=temp,p3=temp,p2=p2->next;
    }
    p3->next=NULL;
    return(head);
}

void print(struct List *p)
{
    while(p!=NULL)
    {
        printf("%3d",p->n);
        p=p->next;
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值