题目描述
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
参考答案
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 ListNode res(0); // content 13 ListNode* cur = &res; // pointer cur = taking addree of res 14 // *content. &pointer-> 15 16 while(l1&&l2){ 17 if(l1->val > l2 ->val){ 18 cur->next = l2; 19 l2 = l2->next; 20 }else{ 21 cur->next = l1; 22 l1 = l1->next; 23 } 24 cur = cur->next; 25 } 26 cur->next = l2?l2:l1; 27 return res.next; 28 } 29 };
答案解析
新建一个空节点,不是地址,而是内容,然后将该内容对应的地址,附给一个cur指针。
进行loop
返回的时候,因为对于struct而言,提取成员时,内容使用 点,指针使用 -> 。