21. Merge Two Sorted Lists
来源:互联网 发布:投资公司的网络销售 编辑:程序博客网 时间:2024/05/29 19:43
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* newhead=new ListNode(-1);//新链表头结点 ListNode* temp=newhead;//临时头结点,代替newhead变换。因为newhead->next始终必须指向头结点。所以不能直接使用newhead去移动 while(l1&&l2) { if(l1->val<l2->val) { temp->next=l1; l1=l1->next; } else { temp->next=l2; l2=l2->next; } temp=temp->next;//temp向后移 } temp->next=l1?l1:l2; return newhead->next; }};
阅读全文
0 0
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 【C++】C/C++中static关键字作用总结
- hexo YAMLException: cannot read a block mapping entry; a multi line key may not be an implicit key a
- 实现pow函数
- 2017年8月18日模拟9(smoj2218、2044、2103,动态规划,动态规划、树链剖分)
- Mybatis学习(六)mybatis与hibernate区别与应用场景
- 21. Merge Two Sorted Lists
- C语言中的 (void*)0 与 (void)0
- 设计模式---构造者模式
- CODECHEF Palindromic Game
- C++中 atexit函数 exit函数
- JetBrains正式发布Kotlin 1.0:JVM和Android上更好用的语言
- python爬虫上手 笔记<4>
- Markdown的一些语法(好难记啊QAQ)
- mvc、mvp 和mvvm区别