You are on page 1of 9

Data Structures in Java

Linked List
Notice that we cannot get to any part of the list
Structure of a linked list without starting at the head and following each
node's next reference. Check that you understand
that head.data is equal to 36, head.next.data
The only identifier here is is equal to 85 and head.next.next.next.data
head head. It is a reference to is equal to 215. We don't normally use
a node: the first one in next.next.next… Instead we use a while loop to
the list. traverse the list.

36 85 132 215

Each node This happens to The last node has a next


contains data be a linked list of value of null. That means it
and a reference ints, but it could doesn't point to another node.
to the next be strings or This is how we know we've
node. other objects. reached the end of the list.
The Node class The LinkedList class
Two member variables (aka fields, Variables:

attributes): ● Node head

● int data Methods:

● Node next The methods you implement depend on what you want to do
● Er… with the list. Let's make a linked list that we can use to
create a stack:
● That's it!
● void addAtHead(int)
● int removeAtHead()

We also need to make some sort of print method, so we can


see what's going on:

● void print()
Task Think about how The LinkedListDemo
many classes you class only instantiates
will need and set and calls methods from
1. Open up a new Java project called the LinkedList class.
LinkedListDemo them up first.
There should be no
2. Add a LinkedList class and a Node class to the reference to Nodes in the
same file LinkedListDemo class.
3. Code the Node class In your addAtHead
4. Code the addAtHead and removeAtHead and removeAtHead
methods of your LinkedList class methods, you will
need to declare In the print method
5. See if you can can code the print method
temporary local you start at the
6. Use the main method of the LinkedListDemo Node variables to head and set up a
class to instantiate a LinkedList, add/remove help you out. while loop to keep
some nodes, and print the result following the next
references until you
hit one that is null.
Stage 1
Stage 2
Stage 3
Stage 4
Stage 5

You might also like