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

Merge Two Sorted Lists

时间:2015-01-31 16:22:38      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

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<iostream>
#include<vector>
using namespace std;

//Definition for singly - linked list.
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
	ListNode*ResultList = new ListNode(0);
	ListNode*ResultHead = ResultList;
	ListNode*Tmpl1 = l1;
	ListNode*Tmpl2 = l2;
	while (Tmpl1!=NULL&&Tmpl2!=NULL){
		if (Tmpl1->val<=Tmpl2->val){
			ResultHead->next = Tmpl1;
			Tmpl1 = Tmpl1->next;
		}
		else{
			ResultHead->next = Tmpl2;
			Tmpl2 = Tmpl2->next;
		}
		ResultHead = ResultHead->next;
	}
	if (Tmpl1 == NULL&&Tmpl2 != NULL)
		ResultHead->next = Tmpl2;
	else if (Tmpl1 != NULL&&Tmpl2 == NULL)
		ResultHead->next = Tmpl1;
	return ResultList->next;
}


Merge Two Sorted Lists

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43341027

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