Download Singly-Linked List Class and more Study notes Data Structures and Algorithms in PDF only on Docsity!
Singly-Linked List Class
15 - 121 Fall 2020
Margaret Reid-Miller
Exam 1 during class Thursday
have any difficulties and need accommodations.
- Topics include everything except Linked Lists.
- Review Sessions:
- Sean: Today 5pm – 6pm
- Margaret: Wednesday during lab (attendance
not required)
- Leah: Wednesday 5pm - 6pm
How to deal cards in HW5 card game.
- What are two ways to deal a card from a pile?
- pile.remove(0)
- pile.remove(pile.size()-1)
- Which is easier to code?
- Which is the more efficient?
- Never again will you get away with using remove(0)
or add(0, E) if you can reframe the code to use
remove and add at the end of the array list!
O(n)
O(1)
The latter. Why?
Linked Lists
- Advantages:
- Don’t need large blocks of contiguous memory.
- Breaks up an array into little pieces
- Can grow and shrink without copying data.
- Disadvantages:
- Access is sequential. Slow to access the middle of the
list.
- What arrays/ArrayLists do well, linked list do poorly and
vice versa.
An empty linked list has a head
reference equal to null.
- This is very different than Strings or ArrayLists
- If I have an empty String,
- I can still ask for its length and
- check if it is equal to another String.
- If I have an empty ArrayList,
- I can still ask for its size and
- add elements to it.
What does the following Java
statement do to this linked list?
- list = list.next;
"A"
"B" "C"
list
"A" "B" "C"
list
What does the following Java
statement do to this linked list?
- list.next.next.next = list;
A circular linked list!
"A"
"B" "C"
list
list
list.next list.next.next
"A" "B" "C"
list
Write code to go from Before to After
by changing the links only
Before:
After:
"A"
"C"
s
t
t
"B" "D"
"A" "C" "B"
s
"D"
statement order is important!
Write code to go from Before to After
by changing the links only
Before:
After:
"A"
"C"
s
t
t
"B" "D"
"A" "C" "B"
s
"D"
statement order is important!
- s.next.next = t
2.2. tt == t.nextt.next
Write code to go from Before to After
by changing the links only
Before:
After:
"A"
"C"
s
t
t
"B" "D"
"D"
statement order is important!
- s.next.next = t
- t = t.next
- s.next.next.next
= null
"A" "C" "B"
s
A GENERIC LINKED-LIST
CLASS
We want a singly-linked list class that,
from the outside, behaves like an ArrayList.
SinglyLinkedList names;
names = new SinglyLinkedList();
names.add("Margaret");
names.add("Tom");
names.add(0, "Dave");
names.size(); // returns 3
names.get(2); // returns "Tom"
Implementing a Linked List class
For a linked list, what data do I need to keep?
- A reference to the first (head) node
And what’s in a node?
- data
- a reference to the next node in the list
What type should its data be?
So, how should we declare a SinglyLinkedList class?
SinglyLinkedList class
public class SinglyLinkedList {
private Node first;
private int size; // why?
// constructor
public SinglyLinkedList() {
first = _____
size = 0;
}
null;