建议:在对指针*或->之前一定考虑是否为空指针或未初始化指针。
#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; }
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46391641