码迷,mamicode.com
首页 > 其他好文 > 详细

017_合并两个排序的链表

时间:2014-09-06 22:35:14      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:os   io   ar   for   sp   amp   c   new   ad   

#include <iostream> 
#include <vector>
using namespace std;


typedef struct ListNode {
	int data;
	struct ListNode * next;
	ListNode(int d) : data(d), next(NULL){}
};

ListNode *initList(int *array, unsigned int length) {
	
	if(!array) {
		return NULL;
	}

	ListNode * head = NULL;
	head = new ListNode(array[0]);
	ListNode * p = head;
	head->next = NULL;
	
	unsigned int i = 1;
	for(; i < length; i++) {
		p->next = new ListNode(array[i]);
		p = p->next;		
	}

	
	return head;
	
} 

void printList(ListNode *head) {
	
	ListNode * p = head;
	if (!head){
		return;
	}
	while (p && p->next) {
		cout<<p->data<<"->";
		p = p->next; 
	}
	if (p) {
		cout<<p->data<<endl;
	}
	
}

ListNode *merge(ListNode *head1, ListNode *head2) {
	
	ListNode *newHead = NULL;
	ListNode *p1 = head1;
	ListNode *p2 = head2;
	ListNode *p = NULL;
	 
	if(!head1){
		return head2;
	}

	if(!head2){
		return head1;
	}

	p = newHead;

	while(p1 && p2) {
		if(p1->data <= p2->data) {
			if(!newHead) {
				newHead = p1;
				p1 = p1->next;
				newHead->next = NULL;
				p = newHead; 
			} else {
				p->next = p1;
				p1 = p1->next;
				p = p->next;
				p->next = NULL;
				
			}
			
		} else {
			if(!newHead) {
				newHead = p2;
				p2 = p2->next;
				newHead->next = NULL;
				p = newHead; 
			} else {
				p->next = p2;
				p2 = p2->next;
				p = p->next;
				p->next = NULL;
				
			}
		}	
	}
	
	while(p1) {
		if(!newHead) {
				newHead = p1;
				p1 = p1->next;
				newHead->next = NULL;
				p = newHead; 
		} else {
				p->next = p1;
				p1 = p1->next;
				p = p->next;
				p->next = NULL;
				
		}
	}
	
	while(p2) {
		if(!newHead) {
				newHead = p2;
				p2 = p2->next;
				newHead->next = NULL;
				p = newHead; 
		} else {
				p->next = p2;
				p2 = p2->next;
				p = p->next;
				p->next = NULL;
				
		}
	}
	
	return newHead;
}

int main(){ 


	int i = 0;
	unsigned int length1 = 0;
	unsigned int length2 = 0;
	
	
	cin>>length1;
	cin>>length2;
	
	int *array1;
	int *array2;
	ListNode *head1 = NULL;
	ListNode *head2 = NULL;
	
	if(length1 > 0){
		array1 = new int[length1];
		for(i = 0; i < length1; i++) {
			array1[i] = i * 10;
		}
		head1 = initList(array1, length1);
		cout<<"list1:	";
		printList(head1);
		delete []array1;
	} else {
		head1 = NULL;
	} 

	if(length2 > 0){
		array2 = new int[length2];
		for(i = 0; i < length2; i++) {
			array2[i] = i * 5;
		}
		head2 = initList(array2, length2);
		cout<<"list2:	";
		printList(head2);
		delete []array2;
	} else {
		head2 = NULL;
	} 

	ListNode *newHead = merge(head1, head2);
	cout<<"merged List:	";
	printList(newHead);

	return 1;	
}

017_合并两个排序的链表

标签:os   io   ar   for   sp   amp   c   new   ad   

原文地址:http://blog.csdn.net/wyj7260/article/details/39104801

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!