1. 程式人生 > >合併兩個排序連結串列(LintCode)

合併兩個排序連結串列(LintCode)

實現程式碼:
#include <iostream>

using namespace std;


//Definition of ListNode
class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int val) {
        this->val = val;
        this->next = NULL;
    }
};
void display(ListNode *p);
class Solution
{
public:
	/**
	* @param ListNode l1 is the head of the linked list
	* @param ListNode l2 is the head of the linked list
	* @return: ListNode head of linked list
	*/
	ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
	{
		if (l1 == NULL)
		{
			return l2;
		} else if (l2 == NULL)
		{
			return l1;
		}
		ListNode *p1 = l1;
		ListNode *p2 = l2;
		ListNode *pH = NULL;
		ListNode *p = NULL;
		
		while (p1 != NULL && p2 != NULL)
		{
			//cout << p1->val << endl;
			
			if (p1->val > p2->val)
			{
				if (pH == NULL)
				{
					pH = p2;
					p = pH;
					p2 = p2->next;
				} else
				{
					p->next = p2;
					p = p->next;
					p2 = p2->next;
				}
			} else
			{
				if (pH == NULL)
				{
					pH = p1;
					p = pH;
					p1 = p1->next;
				} else
				{
					p->next = p1;
					p = p->next;
					p1 = p1->next;
				}
			}
			//display(pH);
		}
		if (p1 != NULL)
		{
			p->next = p1;
		}
		if (p2 != NULL)
		{
			p->next = p2;
		}
		return pH;
	}
};

void insertListNode(ListNode *p, int *pt, int N)
{
	for (int i = 0; i < N; i++)
	{
		ListNode *tmp = new ListNode(pt[i]);
		p->next = tmp;
		p = p->next;
	}
		
	return;
}
void display(ListNode *p)
{
	if (p == NULL)
		return;
	cout << p->val;
	p = p->next;
	while (p != NULL)
	{
		cout << "->" << p->val;
		p = p->next;
	}
	cout << endl;
	return;
}
int main()
{
	int nums1[] = { 3, 8, 11, 15 };
	int nums2[] = { 2, 4};
	ListNode *p1 = new ListNode(1);
	ListNode *p2 = new ListNode(2);
	insertListNode(p1, nums1, 4);
<span><strong></strong></span><pre name="code" class="cpp">        insertListNode(p1, nums2, 1);
  Solution st;ListNode *p = st.mergeTwoLists(p1, p2);display(p);return 0;}