Ctec2909 Data Structures and Algorithms: Lecture 2 Arrays & Linked Lists
Ctec2909 Data Structures and Algorithms: Lecture 2 Arrays & Linked Lists
Ctec2909 Data Structures and Algorithms: Lecture 2 Arrays & Linked Lists
ALGORITHMS
Lecture 2 Arrays & Linked Lists
Arrays
Arrays are used for storing sequences of values.
All the elements in an array are the same type – e.g. integers,
booleans, doubles, Strings, etc.
34 47 5 74 19 elements
0 1 2 3 4 indices
34 47 5 74
0 1 2 3 4
70
Array operations
In the worst case, all
34 47 5 74
the elements might
0 1 2 3 4 have to move.
Therefore it is O(n)
34 47 5 74 complexity, where n is
0 1 2 3 4 the length of the array.
34 47 70 5 74
0 1 2 3 4
Array operations
Searching for a particular element also requires
searching through the whole array in the worst case –
the worst case is when the element is not in the array.
head tail
This time, each element is stored as a separate object, with a
link to the next element.
Implementation of a Linked List
red blue orange green
A Node has some data (in this case a String) and a link to the next node.
There has to be a way of getting the data and setting the data, and
getting the next link and setting the next link.
Implementation of a Linked List
red blue orange green
public class Node{ This could be other types e.g. int, depending
private String item; on what you want to store in the list.
private Node nextItem;
n3
Implementation of a Linked List
red blue orange green
The LinkedList class represents the list, but we don’t need to store
all the nodes in it.
Each node has a link to the next, so we only need a link to the first
node.
Implementation of a Linked List
red blue orange green
null
public class LinkedList(){ public getHead(){
private Node head; return head;
}
public LinkedList(Node n){ public setHead(Node n){
head = n; head = n;
} }
}// end of class
Implementation of a Linked List
red blue orange green
theHead.next().next().setItem(“yellow”);
This changes the 3rd node to “yellow”.
Linked Lists Insertion
Inserting after a given node:
n1.next().next().setPrevious(n1);
n3 n1.setNext(n1.next().next());
Doubly Linked Lists Deletion
Deleting before a given node:
n3.previous().previous().setNext(n3);
n3.setPrevious(n3.previous().previous());
n1
Tail Element
Doubly-linked lists have a tail element as well as the head.
red blue orange green
head null
tail
This allows the list to be traversed from either end, using the
previous links from the tail or the next links from the head.
Singly-linked lists can also have a tail. This could be useful for
adding to the end of the list.
Circular Linked Lists
Instead of the last element pointing to null, it can point to the
head element.
head
Circular Linked Lists
Adding a node to the start of the list:
Node newItem = new Node(“yellow”, head);
n4.setNext(newItem);
head = newItem;