算法题之合并两个有序单向链表
题目描述
题目分析
代码实现
思路1代码:
public ListNode
mergeTwoLists(ListNode l1
, ListNode l2
) {
if (l1
== null
&& l2
== null
) {
return null
;
}
ListNode head
= new ListNode();
Stack
<ListNode> stack
= new Stack<>();
ListNode head1
= l1
;
ListNode head2
= l2
;
while (head1
!= null
) {
stack
.push(head1
);
head1
= head1
.next
;
}
while (head2
!= null
) {
stack
.push(head2
);
head2
= head2
.next
;
}
while (stack
.size() > 0) {
addNode(head
,stack
.pop());
}
return head
.next
;
}
private void addNode(ListNode head
, ListNode pop
) {
ListNode temp
= head
;
while (true) {
if (temp
.next
== null
) {
break;
}
if (temp
.next
.val
>= pop
.val
) {
break;
}
temp
= temp
.next
;
}
pop
.next
= temp
.next
;
temp
.next
= pop
;
}
思路2代码:
public ListNode
mergeTwoLists(ListNode l1
,ListNode l2
) {
if (l1
== null
) {
return l2
;
}else if (l2
== null
) {
return l1
;
}else if (l1
.val
< l2
.val
) {
l1
.next
= mergeTwoLists(l1
.next
,l2
);
return l1
;
}else {
l2
.next
= mergeTwoLists(l1
,l2
.next
);
return l2
;
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-34728.html