Skip to content

Instantly share code, notes, and snippets.

@mixxorz
Created April 16, 2015 03:43
Show Gist options
  • Save mixxorz/d56b0dd4e0f5b4c5529d to your computer and use it in GitHub Desktop.
Save mixxorz/d56b0dd4e0f5b4c5529d to your computer and use it in GitHub Desktop.
Python Linked List
card1 = {
'name': 'John Smith',
'age': 20,
'gpa': 3.0,
'pointer': None
}
card1
card2 = {
'name': 'Amanda Jones',
'age': 22,
'gpa': 3.5,
'pointer': None
}
card2
# Here's the part where we connect them
card1['pointer'] = card2
card1
# Now card1['pointer'] and card2 are pointing to the same thing
id(card1['pointer'])
id(card2)
# Let's add two more cards to this linked list
card3 = {
'name': 'Carol Lim',
'age': 23,
'gpa': 2.5,
'pointer': None
}
card3
card4 = {
'name': 'Bernard Lee',
'age': 25,
'gpa': 4.0,
'pointer': None
}
card4
# And let's connect them
# Note! Modifying card2 will also modify card1['pointer']
card2['pointer'] = card3
card3['pointer'] = card4 # Remember, they're pointing to the same thing!
# So now we have a linked list with four items and each item is connected in
# In the order 1,2,3,4.
# Here's some code that will print the entire list
current_card = card1
while(current_card is not None):
print('Address: %x' % id(current_card)) # Print in hex format :)
print('Name: %s' % current_card['name'])
print('Age: %d' % current_card['age'])
print('GPA: %f' % current_card['gpa'])
print('Pointer: %x' % id(current_card['pointer']))
print('=========================================') # Print a divider
# Set the current_card to the next item on the linked list
current_card = current_card['pointer']
# It will stop at card4 because card4's pointer is None. current_card will be
# None and the loop will terminate
# Note however that card4's pointer prints an address. That may seem strange,
# until you remember that almost everything in Python is a pointer, in which
# case you'll realize that the address it's pointing to has a value of None.
'%x' % id(None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment