码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Sorted Lists

时间:2015-06-07 09:38:10      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:算法   c++   

建议:在对指针*或->之前一定考虑是否为空指针或未初始化指针。

#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 *p1,*p2,*p3;
		p1 = l1;
		p2 = l2;
		ListNode *l3 = new ListNode(0);
		p3 = l3;
		while(p1 != NULL || p2 != NULL) {
		
			if(NULL == p1) {
				p3->next = p2;
				p3 = p3->next;
				p2 = p2->next;
				continue;
			}
			if(NULL == p2) {
				p3->next = p1;
				p3 = p3->next;
				p1 = p1->next;
				continue;
			}

			if(p1->val <= p2->val) {
				p3->next = p1;
				p3 = p3->next;
				p1 = p1->next;
			}else {
				p3->next = p2;
				p3 = p3->next;
				p2 = p2->next;
			}
		}

		return l3->next;
    }
};

int main() {
	ListNode node2(2),node4(4),node6(6),node8(8),node10(10),node12(12);
	node2.next = &node6; node6.next = &node10; node10.next = NULL;
	node4.next = &node8; node8.next = &node12; node12.next = NULL;
	ListNode * l1 = &node2;
	ListNode * l2 = &node4;

	Solution solution;
	ListNode *p4 = solution.mergeTwoLists(l1, l2);
	while(p4 != NULL) {
		cout << p4->val << "  ";
		p4 = p4->next;
	}

	getchar();
	return 1;
}

Merge Two Sorted Lists

标签:算法   c++   

原文地址:http://blog.csdn.net/guanzhongshan/article/details/46391641

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!