题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/* struct ListNode { int val; struct ListNode next; ListNode(int x) : val(x), next(NULL) { } };/ //非递归法 class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode *p = pHead1; ListNode *q = pHead2; int flag = 0; ListNode *tmp = nullptr; if(p == nullptr) return q; if(q == nullptr) return p; if(p->val >= q->val){ flag = 1; } while(p != nullptr & q != nullptr){ if(p->val >= q->val){ while(q->next!=nullptr && (q->next)->val <= p->val){q = q->next;} tmp = q->next; q->next = p; q = tmp; } else{ while(p->next!=nullptr && (p->next)->val <= q->val){p = p->next;} tmp = p->next; p->next = q; p = tmp; } } if(flag==1){return pHead2;} else{return pHead1;} } };