Created
May 25, 2022 17:21
-
-
Save oreillyross/07aff5646aec51f50881bd9d27e96d18 to your computer and use it in GitHub Desktop.
This is the core pattern to traverse a linked list in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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