21、合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
代码实现:
#include <stdio.h>
#include "stdlib.h"
struct LNode{
int val;
struct LNode *next;
};
//创建链表
struct LNode *creatlist(){
int val=0;
printf("shuru:");
scanf("%d",&val);
struct LNode*head=NULL;
struct LNode*current=NULL;
while(val!=-1){
struct LNode*node= (struct LNode *)malloc(sizeof(struct LNode));
node->val=val;
node->next=NULL;
if(head==NULL){
head=node;
current=node;
}else{
current->next=node;
current=node;
}
scanf("%d",&val);
}
return head;
}
//合并两个链表
struct LNode *mergelist(struct LNode *list1,struct LNode *list2){
struct LNode *head, *p, *q;
head = (struct LNode *) malloc(sizeof(struct LNode));
head->next=NULL;
q = head;
while(list1!=NULL&&list2!=NULL){
p=(struct LNode *)malloc(sizeof(struct LNode));
if(list1->val<list2->val){
p->val= list1->val;
p->next=NULL;
q->next=p;
q=p;
list1=list1->next;
}else
{
p->val = list2->val;
p->next = NULL;
q->next = p;
q = p;
list2 = list2->next;
}
}
if(list1!=NULL){
p->next=list1;
}
if(list2!=NULL){
p->next=list2;
}
return head->next;
}
//打印链表
struct LNode* printlist (struct LNode*head){
struct LNode *cur=head;
printf("hebing");
while(cur!=NULL){
printf("%d ",cur->val);
cur=cur->next;
}
}
int main(){
struct LNode *list1=creatlist();
struct LNode *list2=creatlist();
struct LNode *result= mergelist(list1,list2);
printlist(result);
}