题目描述
- 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
参考答案
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode(int x) : val(x), next(NULL) {}
- * };
- */
- class Solution {
- public:
- ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
- ListNode res(0); // content
- ListNode* cur = &res; // pointer cur = taking addree of res
- //*content. &pointer->
- while(l1&&l2){
- if(l1->val> l2 ->val){
- cur->next = l2;
- l2 = l2->next;
- }else{
- cur->next = l1;
- l1 = l1->next;
- }
- cur = cur->next;
- }
- cur->next = l2?l2:l1;
- return res.next;
- }
- };
答案解析
新建一个空节点, 不是地址, 而是内容, 然后将该内容对应的地址, 附给一个 cur 指针.
进行 loop
返回的时候, 因为对于 struct 而言, 提取成员时, 内容使用 点, 指针使用 -> .
来源: http://www.bubuko.com/infodetail-3229481.html