Array&Linked List New
Array&Linked List New
(Section 4)
◼ Arrays
◼ Linked Lists
Singly 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.
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)
{ 1 0
2 0
int[] values = new int[5]; 3 0
0
for (int i = 1; i < 5; i++) { 4
values[i] = i + values[i-1];
After the first iteration
}
0 0
values[0] = values[1] + values[4]; 1 1
2 0
} 0
3
} 4 0
12
Multi-Dimensional Arrays
13
Multi-Dimensional Arrays (cont…)
◼ Two-Dimensional Array Example:
14
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 elements need to be shifted down before insertion and shifted up after
deletion.
15
Operations on Array (cont…)
16
Records
17
Records (cont…)
18
Array of Records
◼ If we need to define a combination of elements and at the same time
some attributes of each element, we can use an array of records.
19
Array of Records (cont…)
◼ Example:
20
Array of Records (cont…)
21
Arrays versus Array of Records
22
Arrays: The Pros & Cons
◼ Pros:
Fast element access
◼ Cons:
While many applications require resizing, static arrays
23
Linked Lists
24
Introduction
◼ Storing data items in arrays has at least two limitations
The array size is fixed once it is created: Changing the size of the array requires
creating a new array ad then copying all data from the old array to the new array
The data items in the array are next to each other in memory: Inserting an item
inside the array requires shifting other items
If each node has a data field and a reference field to another node called next or
successor, the sequence of nodes is referred to as a singly linked list
The first node is called head and the last node is called tail
25
Linked Structures
26
Linked Structures (cont…)
27
Linked Structures (cont…)
28
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 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
29
Linked Lists (cont…)
Linked List
Jane Anne Bob
30
Linked Lists (cont…)
node
A
data pointer
31
Linked Lists (cont…)
◼ To access each node in the list you must follow the references
from one node to the next
System.out.println(current);
current = current.next;
32
Linked Lists Operations
MakeEmpty
InsertNode Transformers
DeleteNode
IsEmpty
FindNode Observers
DisplayList
33
Linked Lists Operations (cont…)
◼ To insert a node at the front of the list, first point the new node to
the front node, then reassign the front reference
34
Linked Lists Operations (cont…)
35
Linked Lists Operations (Inserting a Node)
◼ Before insertion into a linked list, we first apply the searching algorithm.
If the flag returned from the searching algorithm is false, we will allow
insertion, otherwise we abort the insertion algorithm, because we do
not allow data with duplicate values.
36
Linked Lists Operations (Deleting a node)
◼ Two cases:
◼ In other words, the deletion of the last and the middle nodes can be
done by the same process.
37
Linked Lists Operations (Retrieving a node)
◼ Retrieving uses only the cur pointer, which points to the node
found by the search algorithm.
38
Linked Lists Operations (Traversing a node)
39
Variations of Linked Lists
40
Variations of Linked Lists (cont…)
A doubly
linked list
contains next
and previous
members
A single
linked list
contains only
a next
member.
41
Variations of Linked Lists (cont…)
A B C
Head
42
Variations of Linked Lists (cont…)
2 8 3 5
Circular singly linked list
list
5 2 8 3
Circular doubly linked list
43
Singly Linked Lists
element node
element
link to the next node
A B C D
44
Singly Linked Lists
45
Singly Linked Lists
Algorithm addFirst(v)
46
Singly Linked Lists
2. Allow garbage
collector to reclaim the
former first node
47
Singly Linked Lists
Algorithm removeFirst()
if ( head = null )
t = head ;
head = head.getNext();
48
Singly Linked Lists
49
Singly Linked Lists
Algorithm addLast(v)
tail.setNext(v); //make the old tail node point to the new node
50
Singly Linked Lists
51
Singly Linked Lists
elements
53
Doubly Linked Lists (cont…)
Advantage:
A B C
5 10 2
Head
54
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; }
} 55
Doubly Linked Lists
header trailer
header trailer
Algorithm addFirst(v)
57
Doubly Linked Lists
header trailer
header trailer
Algorithm addAfter(v,z)
59
Doubly Linked Lists
header trailer
header trailer
Algorithm removeLast():
if ( size = 0 )
trailer.setPrev(u);
u.setNext(trailer);
v.setPrev(null);
v.setNext(null);
61
Doubly Linked Lists
header trailer
header trailer
Algorithm remove(v):
u.setNext(w);
v.setNext(null);
63
Applications of linked lists
◼ 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.
65
Linked List Example Using JAVA (cont…)
import java.util.LinkedList;
66
Linked List Example Using JAVA (cont…)
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);
}
}
} 67
67
Singly Linked Lists Analysis
- Complexity Analysis -
Note: some ideas in this section are repeated in another way, or another
representation way
68
Singly Linked Lists
69
Singly Linked Lists
70
Singly Linked Lists
Traversal
e = e.next;
72
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.
73
Singly Linked Lists
- Complexity Analysis -
Note: some ideas in this section are repeated in another way, or another
representation way
76
Doubly Linked Lists
77
Doubly Linked Lists
78
Doubly Linked Lists
Complexity is O(1)
79
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:
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) 82
Summary
◼ An array is a sequenced collection of elements, normally of the same data type.
◼ 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.
◼ 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.
83
References
◼ Java Software Structures - Designing and Using Data Structures, 4th edition, Lewis and Chase.
◼ Data Structures and Problem Solving Using Java, 4th edition, Weiss.
◼ A Practical Introduction to Data Structures and Algorithm Analysis, 3rd edition, Shaffer.
◼ Data Structures and Algorithms in Java, 6th edition, Goodrich, Tamassia and Goldwasser.
84
Any Question
???
85