21、合并两排序链表
合并两个已排序的链接列表并将其作为新列表返回。新列表应该通过拼接前两个列表的节点来完成。Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
#### 解法一:先将两链表结点值进行比较添加到新链表中,之后将剩余链表结点接在新链表后面。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode node = new ListNode(0);
ListNode head = node;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
node.next = new ListNode(l1.val);
l1 = l1.next;
}else{
node.next = new ListNode(l2.val);
l2 = l2.next;
}
node = node.next;
}
while(l1!=null){
node.next = new ListNode(l1.val);
l1 = l1.next;
node = node.next;
}
while(l2!=null){
node.next = new ListNode(l2.val);
l2 = l2.next;
node = node.next;
}
return head.next;
}
}
解法二:和解法一类似,就是将最后长的链表单独加在新链表之后的语句和前面比较的语句和在了一起
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = null,p = null,p1 = l1,p2 = l2;
while(p1 != null || p2 != null){
if( p2 == null || p1!=null && p1.val <= p2.val){ //small = p1
if( head == null){
head = p1;
p = head;
}else{
p.next = p1;
p = p1;
}
p1 = p1.next;
}else if (p1 == null || p1.val > p2.val){ //small = p2
if(head == null){
head = p2;
p = head;
}else{
p.next = p2;
p = p2;
}
p2 = p2.next;
}
}
return head;
}
解法三:递归求解 很优秀
总是让val值小的结点链表交换到l1链表上,然后,从val值小的结点往下递归,直到其中一条链表结点为空,返回多余链表,连成新链表。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val <= l2.val) l1.next = mergeTwoLists(l1.next, l2);
else {
ListNode n = l1;
l1 = l2;
l1.next = mergeTwoLists(l1.next, n);
}
return l1;
}
}
解法四:直接从原链表上插入另一个链表上比原链表下一结点值小的结点。
class Solution {
public ListNode mergeTwoLists(ListNode a, ListNode b) {
ListNode c = null;
if(a == null) return b;
if(b == null) return a;
if(a.val <= b.val){
c = a;
}
else{
c = b;
b = a;
a = c;
}
while(a.next != null){
if(a.next.val > b.val){
ListNode temp = a.next;
a.next = b;
b = temp;
}
a = a.next;
}
a.next = b;
return c;
}
}
只有第一个解法是本人做的,其他的都是看讨论区,总结的解法,都是大佬写的。
目标:每天一道算法题。
时间:2019-5-29
已完成:2道