Link List
Link List
LINKED LIST
• Each element in the list is called a node, and each node has a reference
to the next node in the list.
• The first node in the list is called the head, and the last node in the list
is called the tail.
Arrange the name of the students according to the first letter of their names
Billy
Neil
Vincent Aaron
Terrence
Harold
John
Arrange the name of the students according to the first letter of their names
• Data
• Link
Node
Data Link
1000
Pointer
LINKED LIST OPERATION
Reading
Read the value at index 2
1. To find the index, the program must begin at index 0 of the linked list.
2. Next follow the link from index 0 to index 1
3. Next follow the link from index 1 to index 2
Searching
• The program needs to start at the first cell and look through each and
every cell until it finds the value it’s searching for.
def index_of(value)
return nil
end
Insertion
• Comparing with arrays, insertion in a linked list will only take one
step O(1).
A linked list provides the flexibility of inserting data to the front of the list
without requiring the shifting of any other data.
“purple”
To be able to do this, it first needs to find the node at index 1 ("blue") so it
can modify its link to point to the newly created node.
“purple”
Inserting into the middle of a linked list takes O(N), just as it does for an
array.
Insertion comparison between Linked List and Array
“purple”
Deletion comparison between Linked List and Array
O(N) O(1) at
O(N) O(1) at end
Deletion beginning
Doubly Linked List
A doubly linked list is like a linked list, except that each node has two
links—one that points to the next node, and one that points to the
preceding node.
def initialize(data)
@data = data
end
end
class DoublyLinkedList
attr_accessor :first_node, :last_node
def initialize(first_node=nil, last_node=nil)
@first_node = first_node
@last_node = last_node
end
end
Since a doubly linked list always knows where both its first and last nodes
are, we can access each of them in a single step, or O(1).
Insertion/Deletion
1. Create a new node (“Sue”) and have its previous node point to the last
node of the linked list (“Zoe”).
2. Change the next node of the last node (“Zoe”) to point to the new
node (“Sue”).
3. Declare the new node (‘Sue”) to be the last node in the linked list.
Inserting data at the end of a doubly linked list is just one step
class Node def remove_from_front
attr_accessor :data, :next_node, :previous_node removed_node = @first_node
def initialize(data) @first_node = @first_node.next_node
@data = data return removed_node
end end
end end