You can implement data structures using "Objects". Objects are just HashMaps but with nicer syntax.
For interviews we usually prefer implementing data structures with HashMaps instead of Objects. For example, here's how we'd make a LinkedList:
But instead of using HashMaps, you might want (or be told) to implement a data structure using objects. Here's how you might implement the above code using objects. We'll assume we already wrote the class ListNode
.
Objects like node1
, node2
, and node3
behave exactly the same as HashMaps. They just have different syntax and let you write less code sometimes. Anything you do with an object, you could have done with a HashMap and functions instead. It's just a matter of preference which to use.
Now that you know about objects, we'll walk you through classes, which create objects.
There are only 2 things about classes you need to know.
1. You can write a function that runs when you create a new object, like when you call x = ListNode()
. The function is always called __init__
.
2. When you define a new function in a Class, you need to give the function an extra input. People usually call it the self
input. This input gives you access to the object you're dealing with. It's automatically passed in, and you don't have to specify it when you actually call the function.
Here's an example of a Class:
And here's an example of how you use this Class: