數據結構實驗之鏈表四:有序鏈表的歸併

數據結構實驗之鏈表四:有序鏈表的歸併

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

分別輸入兩個有序的整數序列(分別包含M和N個數據),建立兩個有序的單鏈表,將這兩個有序單鏈表合併成爲一個大的有序單鏈表,並依次輸出合併後的單鏈表數據。

Input

第一行輸入M與N的值;
第二行依次輸入M個有序的整數;
第三行依次輸入N個有序的整數。

Output

輸出合併後的單鏈表所包含的M+N個有序的整數。

Sample Input

6 5
1 23 26 45 66 99
14 21 28 50 100

Sample Output

1 14 21 23 26 28 45 50 66 99 100

Hint

不得使用數組!

Source


#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
	int data;
	struct node *next;
};
int main(){
	int m,n;
	int i;
	cin>>m>>n;
	struct node *head1,*head2,*p,*tail,*p1,*p2;
	head1=(struct node *)malloc(sizeof(struct node));
	head1->next=NULL;
	tail=head1;
	for(i=0;i<m;i++){
		p=(struct node *)malloc(sizeof(struct node));
		scanf("%d",&p->data);
		p->next=NULL;
		tail->next=p;
		tail=p;
	}
	p1=head1->next;
	
	head2=(struct node *)malloc(sizeof(struct node));
	head2->next=NULL;
	tail=head2;
	for(i=0;i<n;i++){
			p=(struct node *)malloc(sizeof(struct node));
		scanf("%d",&p->data);
		p->next=NULL;
		tail->next=p;
		tail=p;
	}
	p2=head2->next;
	
	
	head1->next=NULL;
	tail=head1;
	free(head2);
	while(p1&&p2){
		if(p1->data>p2->data){
			tail->next=p2;
			tail=p2;
			p2=p2->next;
		}else{
			tail->next=p1;
			tail=p1;
			p1=p1->next;
		}
	}
	if(p1){
		tail->next=p1;
	}else{
		tail->next=p2;
	}
	p=head1->next;
	while(p){
		if(p->next!=NULL){
			printf("%d ",p->data);
		}else{
			printf("%d\n",p->data);
		}
		p=p->next;
	}
	return 0;
}

發佈了72 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章