Linked List
Juan Zhai
[email protected]
Motivation
• An array storing integers 1,4, 10, 19, 6. Insert
the integer 7 between the 10 and the 19.
• O(n) for insertion/deletion
• An array has a fixed size.
• Insertion cannot be done if the array is full.
• More space than needed should be allocated
just to be safe.
Juan Zhai,
[email protected] 2
Linked List
• List of items, called nodes. The order of the nodes
is determined by the address, called the link,
stored in each node. Every node (except the last
node) contains the address of the next node
Hook up units via linking
Allocate units of space on demand
Juan Zhai,
[email protected] 3
Linked List
• Components of a node
– Info: stores the relevant information, like an integer
– Link: stores the address of the next node
(technical: pointer/reference/address)
• Each node can be allocated anywhere in memory,
unrelated to any previously nodes.
• The links bind the nodes together to provide apparent
contiguity while in fact the nodes are disparate
memory areas
Juan Zhai,
[email protected] 4
Properties
• Considering the statement current = head;
• Considering current = current.link;
Properties
Review Class/Object
• A class represents the set of properties or
methods that are common to its objects
• An object represents a real-life entity
– All objects share the attributes and the behaviors of
the class
– Values of those attributes are unique for each object
public class Student {
private String name; [”David”, 001]
[”Lucy”, 002]
private int id;
} Juan Zhai,
[email protected] 12
Implementation
• Class Node
– Represents nodes of a linked list
– It has two instance variables
• Info (of type int, but it can be any other type)
• link (of type Node): a reference to another Node object
public class Node {
private int info;
private Node link;
} Juan Zhai,
[email protected] 13
Array VS Linked List
Operation Array Linked List
Access Random, single step No random, always start
at the beginning
Insertion/ Need to shift entries No perturbation of
Deletion entries
Storage Allocated in one shot, Allocated only when
drawback of needed, but links need
underestimating/ additional space
overestimating space
Juan Zhai,
[email protected] 14
Summary
• Comparison between array and linked list
– Operation execution time
– Memory allocation
• Node implementation