请看题目,利用malloc()函数如何实现将输入的任意个数字连成一个链表?

想要利用malloc()函数实现将输入的任意个数字连成一个链表,并输出链表中的数字,最后撤销链表

慕的地8271018
浏览 573回答 1
1回答

拉丁的传说

#include <stdio.h>#include <malloc.h>struct intnode{int num;intnode *next;};intnode *createlist(int n){intnode *p,*head=NULL;int i;p=(intnode *)malloc(sizeof(intnode));scanf("%d",&p->num);p->next=NULL;head=p;for (i=1;i<n;i++){p->next=(intnode *)malloc(sizeof(intnode));p=p->next;scanf("%d",&p->num);}p->next=NULL;return head;}intnode *sumlist(intnode *a,intnode *b){intnode *pa=a,*pb=b,*p,*head;p=(intnode *)malloc(sizeof(intnode));if (a->num<b->num){p=a;pa=a->next;}else{p=b;pb=b->next;}p->next=NULL;head=p;while(pa!=NULL&&pb!=NULL){if (pa->num<pb->num){p->next=pa;p=pa;pa=pa->next;}else{p->next=pb;p=pb;pb=pb->next;}}if(pb==NULL)while (pa!=NULL){p->next=pa;pa=pa->next;}elsewhile (pb!=NULL){p->next=pb;pb=pb->next;}return head;}void main(){int N1,N2;intnode *p1,*p2,*p;scanf("%d%d",&N1,&N2);p1=createlist(N1);p2=createlist(N2);p=sumlist(p1,p2);while (p!=NULL){printf("%d ",p->num);p=p->next;}printf("\n");}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP