Merge two sorted linked lists
public class MergeLinkedLists {
static class ListNode {
int val;
ListNode next;
public ListNode() {}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode mergedList = new ListNode();
ListNode current = mergedList;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
current.next = list1;
list1 = list1.next;
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next;
}
if (list1 != null) {
current.next = list1;
} else {
current.next = list2;
}
return mergedList.next;
}
public static void main(String[] args) {
// Example usage:
ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
ListNode mergedList = mergeTwoLists(list1, list2);
while (mergedList != null) {
System.out.print(mergedList.val + " ");
mergedList = mergedList.next;
}
}
}
Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space
Output:
1 1 2 3 4 4
Geeks link:
Eric Emanuel shorts represent a lifestyle tied to confidence and individuality. They’ve been embraced by athletes, artists, and streetwear fans alike, becoming a symbol of relaxed luxury and sports-inspired fashion.
ReplyDeleteThere’s a raw, emotional edge to Broken Planet Market that sets it apart in the streetwear space. It feels like a brand that understands its audience and reflects how people actually feel, not just what’s trending.
ReplyDeleteWinter sales make Denim Tears jackets more accessible. Definitely a good option for cold-season fashion. I love how Denim Tears jackets can be worn casually or styled up. Perfect for winter outings.
ReplyDeleteCorteiz joggers have a clean streetwear vibe for winter. They look comfortable for daily wear. The winter sale timing is perfect.
ReplyDeleteI like how the Chrome Hearts hat adds a modern twist to classic streetwear. It’s bold yet balanced. A great piece.
ReplyDeleteBrowsing through newsswing com has been a wonderful experience. The content is always fresh, informative, and relevant, which makes newsswing com stand out as a trustworthy source for news enthusiasts seeking detailed and accurate updates daily.
ReplyDeleteTech enthusiasts will find techactually com to be a treasure trove of information. From gadget reviews to tech tips, every piece of content on techactually is reliable, comprehensive, and highly relevant to anyone passionate about technology.
ReplyDeleteThe editorial team behind this platform does a fantastic job, and newsbrave continually impresses with credible reporting, exclusive updates, and engaging stories that reflect careful research and an unwavering commitment to quality journalism.
ReplyDelete