合并两个排序的链表---递归实现

来源:互联网 发布:怎么禁止mac休眠 编辑:程序博客网 时间:2024/05/19 14:36

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
代码实现:
#include <stdio.h>#include <stdlib.h>typedef struct node{int value;struct node *next;}LinkList;//创建带头结点的单链表void CreateList(LinkList *L){int data;LinkList *p=NULL,*q=L;//p指向新分配的结点,q始终指向链表的尾部printf("input the data: ");while(scanf("%d",&data) !=EOF){p=(LinkList*)malloc(sizeof(LinkList));p->value=data;p->next=NULL;q->next=p;q=p;}}LinkList *Merge(LinkList *pHead1,LinkList *pHead2){if(pHead1==NULL)return pHead2;if(pHead2==NULL)return pHead1; LinkList *pMergeHead=NULL;if(pHead1->value < pHead2->value){pMergeHead=pHead1;pMergeHead->next=Merge(pHead1->next,pHead2);}else{pMergeHead=pHead2;pMergeHead->next=Merge(pHead1,pHead2->next);}return pMergeHead;}void output(LinkList *L){LinkList *p=L;while(p!=NULL){printf("%d\t",p->value);p=p->next;}}int main(){LinkList *a=(LinkList*)malloc(sizeof(LinkList));LinkList *b=(LinkList*)malloc(sizeof(LinkList));CreateList(a);CreateList(b);LinkList *pHead1=a->next;LinkList *pHead2=b->next;output(Merge(pHead1,pHead2));return 0;}


0 0
原创粉丝点击