leetcode 题解 || Merge Two Sorted Lists 问题
来源:互联网 发布:如何申请淘宝介入 编辑:程序博客网 时间:2024/05/17 06:48
problem:
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.
将两个已序链表合并,新链表需要拆分组合原来链表的结点,言外之意,不需要新建结点。
thinking:
(1)突破点在于找到新建链表的第一个结点,找到第一个结点,也就找到了新链表的头指针!!!!
(2)找到了了第一个结点,那么就可以将l1 、l2比较插入到新链表的尾部了
(3)最后将剩下的l1 或者l2结点插入到新链表尾部。
code:
/** * 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 *f=l1;//指向l1 ListNode *s=l2; //指向l2 ListNode *n=NULL;//标记新链表 if(l1==NULL) return l2; if(l2==NULL) return l1; if(l1->val<l2->val)//先找到新链表第一个结点 { n=l1; f=l1->next; } else { n=l2; s=l2->next; } ListNode *newlist=n;//头指针找到了 while((f!=NULL)&&(s!=NULL))//按照数值大小在新链表后端插入 { if(f->val<s->val) { n->next=f; f=f->next; n=n->next; } else { n->next=s; s=s->next; n=n->next; } }//while while(f!=NULL)//将l1剩下的结点插入到新链表的尾部 { n->next=f; f=f->next; n=n->next; } while(s!=NULL)// 将l2剩下的结点插入到新链表的尾部 { n->next=s; s=s->next; n=n->next; } return newlist;//返回新链表的头指针!!! }};
0 0
- leetcode 题解 || Merge Two Sorted Lists 问题
- LeetCode题解:Merge Two Sorted Lists
- LeetCode题解:Merge Two Sorted Lists
- LeetCode题解: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 题解(139): Merge Two Sorted Lists
- LeetCode题解——Merge Two Sorted Lists
- 【leetcode题解】【E】【97】Merge Two Sorted Lists
- LeetCode题解(Week2):21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists 题解 —— Java
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- 学习思想
- 高斯分布概率密度函数(PDF)和累积分布函数(CDF)
- (题目35)题目1201:二叉排序树
- MongoDB 性能优化之分页查询
- 工作总结第十四天
- leetcode 题解 || Merge Two Sorted Lists 问题
- android-- AsyncTask介绍
- STL系列之三 queue 单向队列
- 字符串反转
- Java学习笔记——生成doc说明文档的方法
- Foundation01
- longest palindromic substring(最长回文子串)
- MongoDB 性能优化之索引优化
- Java Random、Map测试