首页 > 代码库 > Merge Two Sorted Lists
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
#include<stdio.h> #include<stdlib.h> typedef struct ListNode { int val; struct ListNode *next; }ListNode; ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *p1; ListNode *p2; ListNode *p3,*head,*head1; if(l1==NULL) return l2; if(l2==NULL) return l1; if(l1->val < l2->val) { head=l1; p2=l2; } else { head=l2; p2=l1; } p1=head; p3=p1; while(p1&&p2){ while(p1->val<p2->val && p1->next!=NULL) {p3=p1;p1=p1->next;} if(p1->next==NULL&&p1->val<p2->val) { p1->next=p2; break; } else{ head1=p3->next; p3->next=p2; p3=p2; p2=head1; } p1=p3; } //p1=head; //while(p1){printf("%d,",p1->val);p1=p1->next;} return head; } void main() { int data,n=0; ListNode *head,*head1,*p1,*head2,*p2; p1=p2=(ListNode *)malloc(sizeof(ListNode)); scanf("%d",&data); p1->val=data; head1=NULL; while(data!=0){ n++; if(n==1) head1=p1; else p2->next=p1; p2=p1; p1=(ListNode *)malloc(sizeof(ListNode)); scanf("%d",&data); p1->val=data; } p2->next=NULL; p1=p2=(ListNode *)malloc(sizeof(ListNode)); scanf("%d",&data); p1->val=data; head2=NULL; n=0; while(data!=0){ n++; if(n==1) head2=p1; else p2->next=p1; p2=p1; p1=(ListNode *)malloc(sizeof(ListNode*)); scanf("%d",&data); p1->val=data; } p2->next=NULL; p1=head1; p2=head2; //while(p1) {printf("%d,",p1->val);p1=p1->next;} //while(p2) {printf("%d,",p2->val);p2=p2->next;} head=mergeTwoLists(p1,p2); //p2=head; //while(p2) {printf("%d,",p2->val);p2=p2->next;} }
Merge Two Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。