Linked Lists Gotchas
Linked lists in Python are strange concept. Here are some tips, tricks, and pitfalls.
1. Once you traverse it, say to print it, you have lost your ability to go back to the beginning. In other words, you can only print it once. You can not print it ever again. Unless you plan ahead to save the head.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = tail = ListNode
dummy_l1_head = l1
dummy_l2_head = l2
# merge l1 and l2 into tail
while l1 and l2:
if l1.val < l2.val:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next
tail.next = l1 or l2
tail = dummy_head
l1 = dummy_l1_head
l2 = dummy_l2_head
# append l2 to l1
tail.next = l1
while tail.next:
tail = tail.next
tail.next = l2
return (dummy_head.next)
1. Once you traverse it, say to print it, you have lost your ability to go back to the beginning. In other words, you can only print it once. You can not print it ever again. Unless you plan ahead to save the head.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = tail = ListNode
dummy_l1_head = l1
dummy_l2_head = l2
# merge l1 and l2 into tail
while l1 and l2:
if l1.val < l2.val:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next
tail.next = l1 or l2
tail = dummy_head
l1 = dummy_l1_head
l2 = dummy_l2_head
# append l2 to l1
tail.next = l1
while tail.next:
tail = tail.next
tail.next = l2
return (dummy_head.next)
Comments
Post a Comment