Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1f8e8cd

Browse files
Create Merge Two Sorted Lists.java
1 parent e940f83 commit 1f8e8cd

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎LinkedList/Merge Two Sorted Lists.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Merge two sorted linked lists and return it as a new list.
3+
The new list should be made by splicing together the nodes of the first two lists, and should also be sorted.
4+
5+
For example, given following linked lists :
6+
7+
5 -> 8 -> 20
8+
4 -> 11 -> 15
9+
The merged list should be :
10+
11+
4 -> 5 -> 8 -> 11 -> 15 -> 20
12+
*/
13+
/**
14+
* Definition for singly-linked list.
15+
* class ListNode {
16+
* public int val;
17+
* public ListNode next;
18+
* ListNode(int x) { val = x; next = null; }
19+
* }
20+
*/
21+
public class Solution {
22+
public ListNode mergeTwoLists(ListNode A, ListNode B) {
23+
if(A == null)
24+
return B;
25+
if(B == null)
26+
return A;
27+
ListNode result = null;
28+
if(A.val <= B.val)
29+
{
30+
result = A;
31+
result.next = mergeTwoLists(A.next, B);
32+
}
33+
else if(A.val > B.val)
34+
{
35+
result = B;
36+
result.next = mergeTwoLists(A, B.next);
37+
}
38+
return result;
39+
}
40+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /