4-07:链表合并

问题:链表合并

合并两个已排序的链表

input: 1->3->5; 2->4->6

output: 1->2->3->4->5->6


class ilistnode
{
public:
	ilistnode(int value, ilistnode* next = NULL)
		:Value(value), Next(next)
	{

	}
	int getvalue() const
	{
		return Value;
	}
	ilistnode* getnext() const
	{
		return Next;
	}
	void setvalue(int value)
	{
		Value = value;
	}
	void setnext(ilistnode* next)
	{
		Next = next;
	}
private:
	int Value;
	ilistnode* Next;
};

ilistnode* mergelist(ilistnode* list1, ilistnode* list2)
{
	if (list1 == NULL)
		return list2;
	else if (list2 == NULL)
		return list1;

	ilistnode* result = new ilistnode(1);
	if (list1->getvalue() < list2->getvalue())
	{
		result = (list1);
		result->setnext(mergelist(list1->getnext(), list2));
	}
	else
	{
		result = (list2);
		result->setnext(mergelist(list1, list2->getnext()));
	}
	return result;
}

Category technology