首页 > 其他 > 详细

leetcode.21------------Merge Two Sorted Lists

时间:2015-02-04 13:05:15      阅读:249      评论: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.


题目:合并两个单链表

思路:先比较两个各链表第一个节点,大的那个节点先设为合并的链表第一个节点,这样就找到了要合成的链表的节点了。

接下来就好办了,把两个链表中节点按照归并排序子过程原理添加到合成的链表中去。


class Solution {
public:
	ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 
	{
		if (l1 == NULL)
			return l2;
		if (l2 == NULL)
			return l1;
		ListNode *p1 = l1;
		ListNode *p2 = l2;
		ListNode* head = NULL;
		ListNode* current = NULL;

		while (p1&&p2)
		{
			if (head == NULL)
			{
				if (p1->val < p2->val)
				{
					head = current = p1;
					p1 = p1->next;
					current->next = NULL;
				}
				else
				{
					head = current = p2;
					p2 = p2->next;
					current->next = NULL;
				}
			}
			else
			{
				if (p1->val < p2->val)
				{
					current->next = p1;
					current = p1;
					p1 = p1->next;
					current->next = NULL;
				}
				else
				{
					current->next = p2;
					current = p2;
					p2 = p2->next;
					current->next = NULL;
				}
			}
		}

		if (p1)
			current->next = p1;
		if (p2)
			current->next = p2;

		return head;
	}
};


leetcode.21------------Merge Two Sorted Lists

原文:http://blog.csdn.net/chenxun_2010/article/details/43483291

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!