Merge Two Sorted Lists
Definition for singly-linked list.
/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
Method 1: (Double-Pointer)
class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *p1 = NULL; ListNode **p2 = &p1; // declare a double pointer while(l1&&l2){ if(l1->val<=l2->val){ *p2 = l1; // For first loop, p1 stores the entry of Linked List l1 = l1->next; }else{ *p2 = l2; // For first loop, p1 stores the entry of Linked List l2 = l2->next; } p2 = &((*p2)->next); // After first loop, p2 stores the address of the Linked List } if(l1) *p2=l1; else *p2=l2; return p1; } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步