LeetCode(21)-Merge Two Sorted Lists
来源:互联网 发布:贵阳大数据产业博览会 编辑:程序博客网 时间:2024/06/07 00:11
问题描述:
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.
问题分析:
合并两个有序的链表,考察对链表的操作,比较经典的题目
解题方法;
/** * 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 *start, *cur; if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l1->val < l2->val ){ cur = start = l1; l1 = l1->next; } else{ cur = start = l2; l2 = l2->next; } while(l1 != NULL && l2 != NULL){ if(l1->val < l2->val ){ cur->next = l1; cur = l1; l1 = l1->next; } else{ cur->next = l2; cur = l2; l2 = l2->next; } } if(l1 !=NULL) cur->next = l1; else cur->next = l2; return start; }};
一开始不懂为什么要定义两个指针,start和cur,后来尝试返回cur时才明白,start一直指向合并链表的头,cur一直在变,所以不能用cur代替。
/** * 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* head = new ListNode(0); //开始我让head = NULL,总是编译不通过,后来改成这样通过了 ListNode* prev = head; if(l1 == NULL) { return l2; } if(l2 == NULL) { return l1; } //prev = head; while(l1 != NULL && l2 != NULL){ if(l1->val < l2->val){ prev->next = l1; l1 = l1->next; prev = prev->next; } else{ prev->next = l2; l2 = l2->next; prev = prev->next; } } if(l1 != NULL){ prev->next = l1; } if(l2 != NULL) { prev->next = l2; } return head->next; }};
这是我第二次做,下次要注意定义链表头节点时要初始化,不能等于NULL.
0 0
- LeetCode(21)Merge Two Sorted Lists
- [LeetCode 21] Merge Two Sorted Lists Solution
- [leetcode 21] Merge Two Sorted Lists
- LeetCode 21:Merge Two Sorted Lists
- LeetCode | #21 Merge Two Sorted Lists
- [Leetcode] 21 - Merge Two Sorted Lists
- leetcode.21------------Merge Two Sorted Lists
- [leetcode]21 Merge Two Sorted Lists
- Leetcode NO.21 Merge Two Sorted Lists
- leetcode[21 链表]Merge Two Sorted Lists
- leetcode-21 Merge Two Sorted Lists
- leetCode #21 Merge Two Sorted Lists
- leetcode 21 Merge Two Sorted Lists
- [Leetcode 21, Easy] Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists
- Leetcode 21 Merge Two Sorted Lists
- 【leetcode】【单链表】【21】Merge Two Sorted Lists
- LeetCode 21 - Merge Two Sorted Lists
- 输入一个集合,求集合内最大乘积
- C++ primer P82 练习3.6
- 云主机安装SVN操作步骤
- 【Redis笔记(四)】 Redis数据结构 - list链表
- AndroidStudio快捷键汇总
- LeetCode(21)-Merge Two Sorted Lists
- 42. Trapping Rain Water leetcode Python 2016 new season
- C++ primer P82 练习3.10
- 详解UML中的关系(泛化、实现、依赖、关联【聚合、组合】)
- CEF中JavaScript与C++交互
- Yii2-高级应用程序模板在同一域名下使用配置
- 同步屏障CyclicBarrier
- C++ primer P94 练习3.17
- VMware Workstation11安装Ubuntu14.04的无线上网和有线上网设置