Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 7, 2017 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/37aaf056dea0c2af83ea2c26430afea0 to your computer and use it in GitHub Desktop.
Save InterviewBytes/37aaf056dea0c2af83ea2c26430afea0 to your computer and use it in GitHub Desktop.
Merge two sorted linked lists
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class MergeTwoLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode sentinel = new ListNode(0);
ListNode current = sentinel;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
if (l1 != null) current.next = l1;
if (l2 != null) current.next = l2;
return sentinel.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment