Beginner Exercises
Linked List Beginner Exercises
Here are some problems designed to help you practice manipulating linked lists. Each problem has two lines. The first line shows how the list starts. The second line shows how the linked list should end.
Your job is to write code that manually manipulates the given start list so it ends up like the end list.
You may create new nodes with
Node.new(data)
You may create temporary variables to refer to nodes,
like
current = root
orcurrent = root.next
You may reassign the
.next
value of any nodeYour solution will be in the format of several small lines of code
manipulating the list.
Here are some example solutions to get you started.
Example 1
Add a node to an empty list
Solution:
Example 2
Add a node at the beginning of the list
Solution:
Problem 1
Add a node in the second place
Problem 2
Add a node to the end
Problem 3
Add a node second to the end
Problem 4
Delete the first node from the list.
Problem 5
Delete everything from the list.
Problem 6
Manually stutter an existing list (make each item appear twice)
Problem 7
Manually reverse an existing linked list
Iterating Over Linked Lists
Now that you're familiar with manually manipulating linked lists try to write methods that act generally on linked lists.
Contains
Write a method called contiains
that accepts a linked list and a value. The method should iterate over the list and return true if the value exists as data at a node in the list, or otherwise return false.
Get Second-To-Last
Write a method that returns the second to last node in a list. You can assume the list has at least two element in it, or more. You can not assume you know the size of the list. You must use a while loop to iterate through the entire list and find out if a .next
property on a node points to nil
to find the end of the list.
Last updated