Skip to content

Instantly share code, notes, and snippets.

@AbhiAgarwal192
Created August 21, 2020 06:18
Show Gist options
  • Save AbhiAgarwal192/6c52517b85dd2fcec26557d344b6a479 to your computer and use it in GitHub Desktop.
Save AbhiAgarwal192/6c52517b85dd2fcec26557d344b6a479 to your computer and use it in GitHub Desktop.
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
ListNode newList = new ListNode();
ListNode dummyHead = newList;
ListNode l1temp = l1;
ListNode l2temp = l2;
while(l1temp!=null && l2temp!=null){
if(l1temp.val<l2temp.val){
dummyHead.next = new ListNode(l1temp.val);
l1temp = l1temp.next;
}
else{
dummyHead.next = new ListNode(l2temp.val);
l2temp = l2temp.next;
}
dummyHead = dummyHead.next;
}
if(l1temp == null){
while(l2temp!=null){
dummyHead.next = new ListNode(l2temp.val);
l2temp = l2temp.next;
dummyHead = dummyHead.next;
}
}
if(l2temp == null){
while(l1temp!=null){
dummyHead.next = new ListNode(l1temp.val);
l1temp = l1temp.next;
dummyHead = dummyHead.next;
}
}
return newList.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment