03_Arrays and Linked Lists
03_Arrays and Linked Lists
Lecture Scope
Lists
Arrays
Linked Lists
Singly Linked List
Doubly Linked List
Linked Lists Analysis (Complexity Analysis)
With Singly Linked List
With Doubly Linked List
2
Arrays
3
Arrays
Imagine that we have 100 scores. We need to read them, process
them and print them.
We must also keep these 100 scores in memory for the duration
of the program.
We can define a hundred variables, each with a different name, as
shown below
4
Arrays (cont…)
5
Arrays (cont…)
6
Arrays (Declaration)
Example:
double[] myList;
OR
2- datatype arrayRefVar[]; // This style is allowed
Example:
double myList[];
7
Arrays (Storage in Memory)
In the definition:
int [ ] tests;
8
Arrays (Terminology)
In the definition:
int [ ] tests;
tests = new int[ISIZE];
9
Arrays (Terminology) (cont…)
arrayRefVar.length
,For example
myList.length //returns
10
10
Arrays (Accessing Array Elements)
Subscripts
(index) 0 1 2 3 4
11
Arrays (Example)
4 0
;values[i] = i + values[i-1]
1 1
}
2 0
} 3 0
4 0
12
Operations on Array
Although we can apply conventional operations defined for each element of
an array, there are some operations that we can define on an array as a data
structure.
The common operations on arrays as structures are searching, insertion,
deletion, retrieval and traversal.
Although searching, retrieval and traversal of an array is an easy job,
insertion and deletion is time consuming.
The elements need to be shifted down before insertion and shifted up after
deletion.
An array is a suitable structure when a small number of insertions and
deletions are required, but a lot of searching and retrieval is needed.
13
Operations on Array (cont…)
14
Arrays: The Pros & Cons
Pros:
Fast element access
Cons:
Required size is not always immediately available
While many applications require resizing, static arrays
are impossible to resize
15
Linked Lists
16
Introduction
17
Introduction (cont.)
18
Linked Structures
19
Linked Lists
Linked Lists are dynamic data structures that grow and shrink one
element at a time, normally without some of the inefficiencies of
arrays.
A linked list is a series of connected nodes
A B C
Head
We create a new node every time we add something to the List and
we remove nodes when item removed from list and reclaim memory
20
Linked Lists (cont…)
node
A
data pointer
21
Variations of Linked Lists
22
Variations of Linked Lists (cont…)
A doubly
linked list
contains next
and previous
members
A singly linked
list contains
only a next
member.
23
Variations of Linked Lists (cont…)
A B C
Head
2 8 3 5
Circular singly linked list
list
5 2 8 3
Circular doubly linked list
25
Singly Linked Lists
A B C D
26
Singly Linked Lists - Insertion
27
Insertion (Cases)
28
Insertion (Case)
29
Insertion (Case)
1st Step : Update the next link of a new node, to point to the current head node.
30
Insertion (Case)
31
Add First(cont…)
Algorithm addFirst(node)
32
Insertion (Case)
33
Insertion (Case)
34
Insertion (Case)
35
Add Last (cont…)
Algorithm addLast(node)
node.next = null //make the new node node point to null object
tail.next = node //make the old tail node point to the new node
//if there is no tail pointer then you have to traverse the list
to the last node
36
Insertion (Case)
37
Insertion (Case)
38
Insertion (Case)
39
Singly Linked List: Deletion
• Deleting a node from a linked list is also
straightforward but there are a few cases
we need to account for:
– The list is empty; or
– The node to remove is the only node in
the linked-list; or
– We are removing the head node; or
– We are removing the tail node; or
– The node to remove is somewhere in
between the head and tail; or
– The item to remove doesn’t exist in the
linked-list 40
Singly Linked List: Deletion
Algorithm
41
Singly Linked List: Deletion
Algorithm
42
Doubly Linked Lists
elements
43
Doubly Linked Lists (cont…)
A B C
5 10 2
Head
44
The Node Class of Doubly Linked List
/** Node of a doubly linked list of strings */
public class DNode {
protected String element; // String element stored by a node
protected DNode next, prev; // Pointers to next and previous nodes
/** Constructor that creates a node with given fields */
public DNode(String e, DNode p, DNode n) {
element = e;
prev = p;
next = n; } /** Returns the element of this node */
public String getElement() { return element; } /** Returns the previous node of this node */
public DNode getPrev() { return prev; } /** Returns the next node of this node */
public DNode getNext() { return next; } /** Sets the element of this node */
public void setElement(String newElem) { element = newElem; }
/** Sets the previous node of this node */
public void setPrev(DNode newPrev) { prev = newPrev; }
/** Sets the next node of this node */
public void setNext(DNode newNext) { next = newNext; }
} 45
Doubly Linked Lists
heade trailer
r
heade trailer
r
heade trailer
r
heade trailer
r
heade trailer
r
heade trailer
r
heade trailer
r
heade trailer
r
A linked list is a very efficient data structure for sorted list that will go through
many insertions and deletions.
A linked list is a dynamic data structure in which the list can start with no
nodes and then grow as new nodes are needed.
A node can be easily deleted without moving other nodes, as would be the
case with an array.
For example, a linked list could be used to hold the records of students in a
school. Each quarter or semester, new students enroll in the school and
some students leave or graduate.
51
JAVA LinkedList Example
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) throws IOException
{ LinkedList list = new LinkedList();
Output
list.add(new Integer(10));
list.add(new Integer(20));
list.add(new Integer(30)); 10
for(int i=0; i<list.size(); i++) 20
{
Integer temp = (Integer)list.get(i); 30
System.out.println(temp); 30
}
for(int i=list.size()-1; i>=0; i--) 20
{ Integer temp = (Integer)list.get(i); 10
System.out.println(temp);
}
}
52
}
52
Singly Linked Lists Analysis
- Complexity Analysis -
Note: some ideas in this section are repeated in another way, or another
representation way
53
Singly Linked Lists
54
Singly Linked Lists
55
Singly Linked Lists
Traversal
e = e.next;
57
Singly Linked Lists
Searching
To search for an element, we traverse from head until we locate the object.
Example: Count the number of nodes with data field equal to a given object.
58
Singly Linked Lists
- Complexity Analysis -
Note: some ideas in this section are repeated in another way, or another
representation way
61
Doubly Linked Lists
62
Doubly Linked Lists
63
Doubly Linked Lists
Complexity is O(1)
64
Doubly Linked Lists
Traversal
For DoublyLinked list, traversal can be done in either direction: forward, starting from
head, or backward starting from tail.
Element e = head; Element e = tail;
while (e != null) { while (e != null) {
//do something //do something
e = e.next; e = e.previous;
} }
Traversal (cont…)
Example: The following computes the sum of the last n nodes:
public int sumLastNnodes(int n){
if(n <= 0)
throw new IllegalArgumentException("Wrong: " + n);
if(head == null)
throw new ListEmptyException();
Deletion
To delete an element, we use either the extract method of DoublyLinkedList or that
of the Element inner class.
public void extract(Object obj){
Element element = head;
while((element != null) && (!element.data.equals(obj)))
element = element.next;
if(element == null)
throw new IllegalArgumentException("item not found");
if(element == head) {
head = element.next;
if(element.next != null)
element.next.previous = null;
}else{
element.previous.next = element.next;
if(element.next != null)
element.next.previous = element.previous;
}
if(element == tail)
tail = element.previous;
}
Complexity is O(n) 67
Summary
An array is a sequenced collection of elements, normally of the same data type.
An alternative to array-based implementations are linked structures.
A linked structure uses object references to create links between objects.
A linked list dynamically grows as needed and essentially has no capacity limitations.
The order in which references are changed is crucial to maintaining a linked list.
Linked list can be Singly-Linked or Doubly-Linked.
Each node in a singly linked list stores element and link to the next node.
Each node in a doubly linked list stores element, link to the previous node and link to the
next node.
In circular linked lists, the last node points to the first node of the list.
Java has a LinkedList class defined as part of the Java collection framework.
So, you simply declare an instance of the LinkedList class and call member methods as
required.
68
References
Java Software Structures - Designing and Using Data Structures, 4th edition, Lewis and Chase.
Data Structures and Problem Solving Using Java, 4th edition, Weiss.
Data Structures & Algorithms in Java, 3rd edition, Drozdek.
Data Structures and Algorithm Analysis in Java, 3rd edition, Weiss.
Algorithms, 4th edition, Sedgewick and Wayne.
A Practical Introduction to Data Structures and Algorithm Analysis, 3rd edition, Shaffer.
Data Structures and Algorithms in Java, 6th edition, Goodrich, Tamassia and Goldwasser.
Foundations of Computer Science, 2nd Edition, Forouzan and Ferous.
www.asyrani.com
http://faculty.kfupm.edu.sa/ICS/jauhar/ics202/
69
Any Question
???
70