首页 > 其他 > 详细

[leetcode] 17. Merge Two Sorted Lists

时间:2014-11-25 00:00:13      阅读:357      评论: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.

就是算导里面的第一个算法讲解,但是我的C++水平实在太渣,所以对于链表的操作很蠢,但还好完成了。题解如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 
	{
		if (l1 == NULL && l2 == NULL)
		{
			return NULL;
		}

		if (l1 == NULL || l2 == NULL)
		{
			return (l1 == NULL) ? (l2) : (l1);
		}
		ListNode *aspros, *deferos, *root;
		aspros = deferos = new ListNode(0);
		if (l1->val <= l2->val)
		{
			aspros->val = l1->val;
			aspros->next = NULL;
			l1 = l1->next;
		}
		else
		{
			aspros->val = l2->val;
			aspros->next = NULL;
			l2 = l2->next;
		}
		root = aspros;

		while (l1 && l2)
		{
			if (l1->val <= l2->val)
			{
				aspros = new ListNode(0);
				aspros->val = l1->val;
				aspros->next = NULL;
				deferos->next = aspros;
				deferos = aspros;
				l1 = l1->next;
			}
			else
			{
				aspros = new ListNode(0);
				aspros->val = l2->val;
				aspros->next = NULL;
				deferos->next = aspros;
				deferos = aspros;
				l2 = l2->next;
			}
		}

		while (l1)
		{
			aspros = new ListNode(0);
			aspros->val = l1->val;
			aspros->next = NULL;
			deferos->next = aspros;
			deferos = aspros;
			l1 = l1->next;
		}

		while (l2)
		{
			aspros = new ListNode(0);
			aspros->val = l2->val;
			aspros->next = NULL;
			deferos->next = aspros;
			deferos = aspros;
			l2 = l2->next;
		}
		

		return root;
	}
};

 

这个就是因为我不会初始化链表,所以在一开始的地方非常蠢,作了两个判断,一个是l1与l2都为NULL的情况,另一个是它俩有一个是空的情况,可以直接弹出,接着就是合并了。

[leetcode] 17. Merge Two Sorted Lists

原文:http://www.cnblogs.com/TinyBox/p/4119927.html

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