Skip to content

Instantly share code, notes, and snippets.

@the-fejw
Created January 28, 2015 01:10
Show Gist options
  • Save the-fejw/d8976cd77b704bb5c76e to your computer and use it in GitHub Desktop.
Save the-fejw/d8976cd77b704bb5c76e to your computer and use it in GitHub Desktop.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val > l2.val:
newHead = l2
l2 = l2.next
else:
newHead = l1
l1 = l1.next
p = newHead
while l1 or l2:
if l1 and l2:
if l1.val > l2.val:
p.next = l2
l2 = l2.next
else:
p.next = l1
l1 = l1.next
elif l1:
p.next = l1;
break;
else:
p.next = l2
break;
p = p.next
return newHead
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment