两个有序数列的合并(链表的应用)(4)

    技术2022-05-19  30

    //两个有序数列的合并#include<stdio.h>#include<stdlib.h>typedef struct No{ int date; No* next;} Node;Node *creat(){ Node* p=NULL,*head=NULL,*tail=NULL;    int x; head=(Node*)malloc(sizeof(Node)); head->date=-100; head->next=NULL; tail=head; scanf("%d",&x); while(x!=-1){  p=(Node*)malloc(sizeof(Node));  p->date=x;  p->next=NULL;  tail->next=p;  tail=p;  scanf("%d",&x); } return head;}void print(Node *head){ Node *p=head->next; while(p!=NULL){  printf(p->next==NULL?"%d/n":"%d ",p->date);  p=p->next; }}void insert(Node *head,int x){ Node *p=head,*q=NULL; q=(Node*)malloc(sizeof(Node)); q->date=x; q->next=NULL; while(p->next!=NULL&&p->next->date<x){/*如果p->next->date<x放前面就不行,                                      因为访问p->next->date是非法的*/  p=p->next; } //printf("p->next=%d x=%d/n",p->next->date,x);这句也是非法的 if(p->next==NULL){  p->next=q; } else{  q->next=p->next;  p->next=q; }}Node* sort(Node *head1,Node *head2){ Node *p1=head1->next,*p2=head2; while(p1!=NULL){  insert(p2,p1->date);  p1=p1->next; } return p2;}main(){ Node *head1,*head2,*head; head1=creat();print(head1); head2=creat();print(head2); head=sort(head1,head2); print(head); return 0;}

     

     

     


    最新回复(0)