leetcode(10)21. Merge Two Sorted Lists
来源:互联网 发布:淘宝客引流文案 编辑:程序博客网 时间:2024/06/05 08:08
题意:对于两个已经排好序的链表,将它们合并成一个新链表
初步分析:这好像也是学数据结构的时候,挺经典的一个题目。方法大概是遍历两个排好序的链表,一边走一边比,谁小插谁(新建一个链表往里插)。直到走到一条走完,然后如果剩下那条还没走完,接着走。现在再来考虑一下异常情况:想了一下,好像不用专门对异常处理,反正都是从头结点判断空,没有不走就是了。
至于插入:要保持顺序,顺着插就可以了: c.next = a; / c.next = b;
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); //最后还要返回,所以要留存 ListNode l3 = head; while(l1 != null && l2!= null) { if(l1.val <= l2.val) //插l1 { l3.next = l1; l1 = l1.next; } else if(l2.val < l1.val) //插l2 { l3.next = l2; l2 = l2.next; } l3 = l3.next; } if(l1 != null) //l1还剩,整个给它接上去。 { l3.next = l1; } if(l2 != null) { l3.next = l2; } return head.next; }}
0 0
- leetcode(10)21. 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
- <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
- shell参数扩展
- Python基本知识点备忘
- SVM在R语言中的使用
- 成员变量详解
- 自定义Content Provider(内容提供器)
- leetcode(10)21. Merge Two Sorted Lists
- Android Webp 完全解析 快来缩小apk的大小吧
- CMSIS-RTOS 时间管理之时间延迟Time Delay
- 目前主要的编成语言及应用方向(领域)
- How to Create a High Availability Setup with Pacemaker, Corosync and Floating IPs on CentOS 7
- 关于Generate SIGNED APK...失败的原因之一
- Flash as3.0笔记 Sound类的使用
- hdu 4283 You Are the One
- #Paper Reading# An Information Retrieval Approach for Chatbot Engines Using Unstructured Documents