21. Merge Two Sorted Lists
来源:互联网 发布:明星淘宝店哪里找 编辑:程序博客网 时间:2024/06/05 20:25
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.
思路:就是设置一个头结点res,如果list1中的当前节点值比list2中的当前节点值小,就将list1的当前节点链接到res中,否则就将list2的当前节点链接到res中,注意,最后还要将list1和list2中剩下的节点链接到res中
代码如下(已通过leetcode)
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode p=l1;
ListNode q=l2;
ListNode a;
if(p.val>q.val) {
a=q;
q=q.next;
} else {
a=p;
p=p.next;
}
ListNode ans=a;
while(p!=null && q!=null) {
if(p.val>q.val) {
a.next=q;
q=q.next;
a=a.next;
} else {
a.next=p;
p=p.next;
a=a.next;
}
}
while(p!=null) {
a.next=p;
p=p.next;
a=a.next;
}
while(q!=null) {
a.next=q;
q=q.next;
a=a.next;
}
return ans;
}
}
- 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
- LeetCode *** 134. Gas Station
- C++组合与继承
- UVA 140 Bandwidth
- ios按钮长按事件
- 爬虫链接
- 21. Merge Two Sorted Lists
- git初建立服务器的几个问题
- elf格式分析
- php trait特性
- C++常用库的函数详解
- 错误记录
- C++设计模式之单例模式
- android studio中批量混淆打包
- xilinx开发总结