合并两个有序链表自测
Posted _BitterSweet
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了合并两个有序链表自测相关的知识,希望对你有一定的参考价值。
struct ListNode
int val;
ListNode* next;
ListNode(int _val): val(_val),next(nullptr)
;
ListNode* merge(ListNode* l1, ListNode* l2)
if(l1 == nullptr) return l2;
if(l2 == nullptr) return l1;
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
while(l1 && l2)
if(l1 -> val <= l2 -> val)
cur -> next = l1;
l1 = l1 -> next;
else
cur -> next = l2;
l2 = l2 -> next;
cur = cur -> next;
cur -> next = l1 ? l1 : l2;
return dummy -> next;
int main(void)
ListNode* node0 = new ListNode(0);
ListNode* node1 = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(1);
ListNode* node5 = new ListNode(4);
node0 -> next = node1;
node1 -> next = node2;
node2 -> next = node3;
node3 -> next = nullptr;
node4 -> next = node5;
node5 -> next = nullptr;
ListNode* node = merge(node0, node4);
while(node != nullptr)
cout << node -> val << endl;
node = node -> next;
return 0;
以上是关于合并两个有序链表自测的主要内容,如果未能解决你的问题,请参考以下文章