<LeetCode OJ> 21. Merge Two Sorted Lists
来源:互联网 发布:两小无猜网络剧资源 编辑:程序博客网 时间:2024/05/04 06:32
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.
本题答案参考于讨论区
题目说合并成为一个新的有序链表!
用一个指针始终指向值为最小的链表头,用一个临时指针始终维护两个链表未被调整过的当前“头”的较小者的指向
举例:链表a,1->3->5->7,链表b,2->4->6->8,调整后的顺序:1->2->3->4->5->6->7->8
一,将较小的链表头作为合并后的头
当前状态:head->1,list1->3,list2->2
二,通过维护一个指针调整较小者的指向
tmphead=head;//tmphead始终指向当前有序的最前端
第一次调整:list2的2较小,则将tmphead的下一个指向2
tmphead->next=head;//即1->2
tmphead=list2;//tmphead始终指向当前有序的最前端
list2=list2->next;//准备下一轮比较list2=4
第二次调整:list1的3较小,则将tmphead的下一个指向3
tmphead->next=head;//即2->3
tmphead=list2;//tmphead始终指向当前有序的最前端
list2=list2->next;//准备下一轮比较list1=5
.........最后记得维护剩余节点
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution {public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { if(list1 == NULL) return list2; if(list2 == NULL) return list1; ListNode* head=NULL;//始终指向新链表的头 ListNode* tmphead=NULL; //维护链表的有序性 //一,将小的链表头作为头 if(list1 -> val < list2 -> val){ head = list1; list1 = list1 -> next; }else{ head = list2; list2 = list2 -> next; } tmphead = head; //二,调整值较小的节点的指向 while(list1 != NULL && list2 != NULL){ if(list1 -> val < list2 -> val){ tmphead -> next = list1; tmphead = list1; list1 = list1 -> next; }else{ tmphead -> next = list2; tmphead = list2; list2 = list2 -> next; } } //三,维护剩余的节点指向 if(list1 != NULL) tmphead -> next = list1; if(list2 != NULL) tmphead -> next = list2; return head; }};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50358232
原作者博客:http://blog.csdn.net/ebowtang
- <LeetCode OJ> 21. Merge Two Sorted Lists
- LeetCode OJ:Merge Two Sorted Lists
- [LeetCode OJ]Merge Two Sorted Lists
- LeetCode OJ Merge Two Sorted Lists
- 【LeetCode OJ 021】Merge Two Sorted Lists
- LeetCode OJ - Merge Two Sorted Lists
- LeetCode OJ - Merge Sorted Array & Merge Two Sorted Lists
- 21. Merge Two Sorted Lists leetcode(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】21. Merge Two Sorted Lists
- [leetcode] 21.Merge Two Sorted Lists
- [leetcode] 21.Merge Two Sorted Lists
- [leetcode] 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists LeetCode
- ubuntu12.04如何挂载WIN7上的共享文件
- mac上安装sublime text3 package control问题
- 中国·乌镇互联网产业园项目总投资约100亿元
- 性能测试中AIX服务器资源监控与瓶颈分析-1
- Android开发——listview中嵌套checkBox复选框实现单选、全选删除列表内容
- <LeetCode OJ> 21. Merge Two Sorted Lists
- 爱奇艺宣布正式启动动漫IP制作开发计划
- 数据库_Mysql_mysql中char,varchar与text类型的区别和选用
- golang SQLDriverConnect: {IM005} [Microsoft][ODBC 驱动程序管理器] 驱动程序的 SQLAllocHandle on SQL_HANDLE_DBC 失败
- Windows简单入门-送给第一次使用电脑的朋友
- CSS样式覆盖规则
- android中的EventBus
- libjpeg 库的安装
- C++ 动态规划0-1背包问题