Movatterモバイル変換


[0]ホーム

URL:


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

Commit4f8e07c

Browse files
authored
Merge pull requestneetcode-gh#67 from vrindavan/main
21-Merge-Two-Sorted-Lists Recursion alernative solution
2 parentsb20df5c +7617e37 commit4f8e07c

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

‎java/21-Merge-Two-Sorted-Lists.java‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,35 @@ public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
2727
prev.next =list1 !=null ?list1 :list2;
2828
returnroot.next;
2929
}
30-
}
30+
}
31+
32+
// Solution using Recursion
33+
/**
34+
* Definition for singly-linked list.
35+
* public class ListNode {
36+
* int val;
37+
* ListNode next;
38+
* ListNode() {}
39+
* ListNode(int val) { this.val = val; }
40+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
41+
* }
42+
*/
43+
classSolution {
44+
publicListNodemergeTwoLists(ListNodelist1,ListNodelist2) {
45+
ListNodehead =newListNode(0);
46+
47+
if(list1 ==null &&list2 ==null)returnnull;
48+
if(list1 ==null)returnlist2;
49+
if(list2 ==null)returnlist1;
50+
51+
if(list1.val >list2.val) {
52+
head =list2;
53+
list2 =list2.next;
54+
}else {
55+
head =list1;
56+
list1 =list1.next;
57+
}
58+
head.next =mergeTwoLists(list1,list2);
59+
returnhead;
60+
}
61+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp