【Leetcode】Merge Two Sorted Lists

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.

合并两个已排好序的数组

代码

#include <iostream>
using namespace std;

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

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    	ListNode* p = new ListNode(0);
    	ListNode* head = p;
    	while(l1&&l2) {
	    	if(l1->val<l2->val) {
	    		p->next = l1;
	    		l1 = l1->next;
	    	} else {
	    		p->next = l2;
	    		l2 = l2->next;
	    	}
	    	p = p->next;
	    }
	    if(l1) {
    		p->next= l1;
    	}
    	if(l2) {
	    	p->next= l2;
	    }
	    return head->next;
    }
};

int main() {
	int a1[] = {
		1,3,5,7,9
	};
	int a2[] = {
		2,4,6,8,10
	};
	ListNode* l1 = new ListNode(a1[0]);
	ListNode* l2 = new ListNode(a2[0]);
	ListNode* head1 = l1;
	ListNode* head2 = l2;
	for(int i=1;i<5;i++){
		l1->next = new ListNode(a1[i]);
		l2->next = new ListNode(a2[i]);
		l1 = l1->next;
		l2 = l2->next;
	}
	Solution s;
	ListNode* head = s.mergeTwoLists(head1, head2);
	while(head) {
		cout<<head->val<<" ";
		head=head->next;
	}
	cout<<"\nend"<<endl;
}