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

leetcode_21题——Merge Two Sorted Lists(链表)

时间:2015-06-17 13:16:56      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

Merge Two Sorted Lists

 Total Accepted: 61585 Total Submissions: 188253My Submissions

 

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.

 

Hide Tags
 Linked List
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

#include<iostream>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
	if(l1==NULL)
		return l2;
	if(l2==NULL)
		return l1;
	ListNode *ptr1=l1;//l1,l2作为剩下的未放进新链表的各自链表哦当前头结点指针
	ListNode *ptr2=l2;//
	ListNode *temp;//新链表的尾结点指针
	ListNode *root;//最终的头结点

	if(l1->val<l2->val)
	{
		temp=l1;
		root=l1;
		ptr1=l1->next;
		ptr2=l2;
	}
	else
	{
		temp=l2;
		root=l2;
		ptr1=l1;
		ptr2=l2->next;
	}

	while(1)
	{
		if(ptr2==NULL&&ptr1==NULL)
			break;
		if(ptr1==NULL&&ptr2!=NULL)
		{
			temp->next=ptr2;
			break;
		}
		if(ptr1!=NULL&&ptr2==NULL)
		{
			temp->next=ptr1;
			break;
		}

		if(ptr1->val<ptr2->val)
		{
			temp->next=ptr1;
			ptr1=ptr1->next;
			temp=temp->next;
		}
		else
		{
			temp->next=ptr2;
			ptr2=ptr2->next;
			temp=temp->next;
		}
	}
	return root;
}
int main()
{
	ListNode *root1=new ListNode(2);
	ListNode *root2=new ListNode(1);
	ListNode *ptr=mergeTwoLists(root1,root2);

	cout<<ptr->val<<‘ ‘<<ptr->next->val<<endl;
}

  

leetcode_21题——Merge Two Sorted Lists(链表)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4582683.html

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