File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * public class ListNode {
4+ * int val;
5+ * ListNode next;
6+ * ListNode() {}
7+ * ListNode(int val) { this.val = val; }
8+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+ * }
10+ */
11+ /**
12+ input : two sorted integer linked list
13+ output : merged single linked list with sorted order
14+ constraints:
15+ 1) both linked list can be empty?
16+ yes
17+ 2) both given lists are sorted?
18+ yes
19+ edge :
20+ 1) if both list are empty return null
21+ 2) if one of input lists is empty return the other one
22+
23+ solution 1)
24+ using two pointer
25+
26+ compare the current pointer's value.
27+ get the smaller one, set to the next node
28+
29+ until both pointer reach the end
30+
31+ tc : O(n) sc : O(1)
32+ */
33+ class Solution {
34+ public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
35+ ListNode dummy = new ListNode ();
36+ ListNode p1 = list1 ;
37+ ListNode p2 = list2 ;
38+ ListNode currNode = dummy ;
39+ while (p1 != null && p2 != null ) {
40+ if (p1 .val < p2 .val ){
41+ currNode .next = p1 ;
42+ p1 = p1 .next ;
43+ } else {
44+ currNode .next = p2 ;
45+ p2 = p2 .next ;
46+ }
47+ currNode = currNode .next ;
48+ }
49+
50+ if (p1 == null ) {
51+ currNode .next = p2 ;
52+ } else {
53+ currNode .next = p1 ;
54+ }
55+
56+ return dummy .next ;
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments