patternpythonMinor
Merge two linked lists in Python
Viewed 0 times
mergetwopythonlistslinked
Problem
I have a method which will merger two sorted list together. The function works, but I saw some duplicated code.
Any ideas to make the code more elegant?
Any ideas to make the code more elegant?
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def MergeLists(headA, headB):
head = tail = Node('',None)
while headA or headB:
# duplicated code here
if headA is not None:
if (headB and headA.data<=headB.data) or (headB is None):
tail.next = headA
tail = headA
headA = headA.next
if headB is not None:
if (headA and headB.data <= headA.data) or (headA is None):
tail.next = headB
tail = headB
headB = headB.next
return head.nextSolution
Elegance is in the eye of the beholder; the following (replacing the
duplicated code here part) is certainly less redundant:for i in xrange(2):
if headA is not None:
if ( headB and headA.data<=headB.data) or (headB is None):
tail.next = headA
tail = headA
headA = headA.next
# When i==0, this will flip headA & headB
# When i==1, it will restore them
headA,headB = headB,headACode Snippets
for i in xrange(2):
if headA is not None:
if ( headB and headA.data<=headB.data) or (headB is None):
tail.next = headA
tail = headA
headA = headA.next
# When i==0, this will flip headA & headB
# When i==1, it will restore them
headA,headB = headB,headAContext
StackExchange Code Review Q#113670, answer score: 4
Revisions (0)
No revisions yet.