Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Created May 25, 2022 17:21
Show Gist options
  • Save oreillyross/07aff5646aec51f50881bd9d27e96d18 to your computer and use it in GitHub Desktop.
Save oreillyross/07aff5646aec51f50881bd9d27e96d18 to your computer and use it in GitHub Desktop.
This is the core pattern to traverse a linked list in python
class Node:
def __init__(self, val):
self.val = val
self.next = None
a = Node('A')
b = Node('B')
c = Node('C')
d = Node('D')
a.next = b
b.next = c
c.next = d
# classic imperative solution
def printList(head):
current = head
while current is not None:
print(current.val)
current = current.next
# recursive classic traversal
def printList2(head):
#base case
if head is None:
return None
# do something with each node
print(head.val)
#recursion
printList2(head.next)
# printList(a)
printList2(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment