21. Merge Two Sorted Lists leetcode(lists)
来源:互联网 发布:snmp及编程实现 编辑:程序博客网 时间:2024/05/18 09:12
Merge Two Sorted Lists
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.
方法一、多开辟了一个链表
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(NULL == l1 || NULL == l2) { return (NULL==l1)?l2:l1; } ListNode l3(0); //必须使用这种定义,如果写成ListNode* l3会超时,必须带头节点 ListNode* p1; ListNode* p2; ListNode* p3; p1 = l1; p2 = l2; p3 = &l3; while(p1 && p2) { ListNode* tmp = (ListNode*)malloc(sizeof(ListNode)); if(p1->val <= p2->val) { cout<<"1p1 "<<p1->val<<endl; tmp->val = p1->val; tmp->next = NULL; p1 = p1->next; } else { cout<<"1p2 "<<p2->val<<endl; tmp->val = p2->val; tmp->next = NULL; p2 = p2->next; } p3->next = tmp; p3 = tmp; } while(p1) { cout<<"2p1"<<p1->val<<endl; ListNode* tmp = (ListNode*)malloc(sizeof(ListNode)); tmp->val = p1->val; tmp->next = NULL; p3->next = tmp; p3 = tmp; p1 = p1->next; } while(p2) { cout<<"2p2"<<p2->val<<endl; ListNode* tmp = (ListNode*)malloc(sizeof(ListNode)); tmp->val = p2->val; tmp->next = NULL; p3->next = tmp; p3 = tmp; p2 = p2->next; } return l3.next; //因为带头节点所以必须返回l3.next }
方法二、直接在第一个链表上进行修改,最终返回第一个链表
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(NULL == l1 || NULL == l2) { return (NULL==l1)?l2:l1; } ListNode* p1= l1; ListNode* pre = p1; ListNode* p2 = l2; while(p1 && p2) { ListNode* tmp = (ListNode*)malloc(sizeof(ListNode)); if(p1->val <= p2->val) { pre = p1; p1 = p1->next; } else { if(pre == p1) //注意当pre==p1时表示要将p2的节点插入p1的头节点 { tmp->val = p2->val; tmp->next = pre; pre = tmp; l1 = pre; p2 = p2->next; } else { tmp->val = p2->val; pre->next = tmp; tmp->next = p1; p2 = p2->next; pre = tmp; } } } while(p2) { ListNode* tmp = (ListNode*)malloc(sizeof(ListNode)); tmp->val = p2->val; tmp->next = NULL; pre->next = tmp; pre = tmp; p2 = p2->next; } return l1; }
0 0
- 21. Merge Two Sorted Lists leetcode(lists)
- 【Leetcode】Merge Two Sorted Lists (2 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
- <LeetCode OJ> 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists LeetCode
- leetcode 21. Merge Two Sorted Lists
- Leetcode:21. Merge Two Sorted Lists(JAVA)
- Leetcode ☞ 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- [LeetCode]21. Merge Two Sorted Lists
- 图像去模糊(逆滤波)
- 首页 干货教程 大数据动向 大数据应用 数据可视化 数据分析 投资并购 企业专区 注册 登录 随机森林入门攻略(内含R、Python代码)
- 希尔排序
- 【OpenCV】颜色空间(RGB,HSV与Gray)及图像处理中的颜色识别
- DCI format 5A相关学习
- 21. Merge Two Sorted Lists leetcode(lists)
- Retrofit开发指南
- 一个Android程序员的第一年
- Python3在Windows安装配置及简单试用
- 二叉树的实例化
- 享元模式
- redis在centos下的安装教程
- UVALive 7512 November 11th
- 插件Vimium快捷键&linux vim总结