0% found this document useful (0 votes)
11 views70 pages

03_Arrays and Linked Lists

The document provides an overview of arrays and linked lists, including their definitions, structures, and operations. It details the advantages and disadvantages of arrays, as well as the various types of linked lists such as singly and doubly linked lists, and their insertion and deletion processes. Additionally, it mentions the Java built-in LinkedList class and its usage in programming.

Uploaded by

d865629w2z
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views70 pages

03_Arrays and Linked Lists

The document provides an overview of arrays and linked lists, including their definitions, structures, and operations. It details the advantages and disadvantages of arrays, as well as the various types of linked lists such as singly and doubly linked lists, and their insertion and deletion processes. Additionally, it mentions the Java built-in LinkedList class and its usage in programming.

Uploaded by

d865629w2z
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 70

Arrays & 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…)

 But having 100 different names creates other problems. We need


100 references to read them, 100 references to process them and
100 references to write them. The following Figure shows a diagram
that illustrates this problem.

5
Arrays (cont…)

 An array is a sequenced collection of elements, normally of the


same data type, although some programming languages accept
arrays in which elements are of different types. We can refer to
the elements in the array as the first element, the second element
and so forth, until we get to the last element.

6
Arrays (Declaration)

 Declared using [ ] operator


1- datatype[] arrayRefVar;

Example:

double[] myList;

OR
2- datatype arrayRefVar[]; // This style is allowed

Example:

double myList[];

7
Arrays (Storage in Memory)

 In the definition:
int [ ] tests;

tests = new int[SIZE]; // SIZE is 5

allocates the following memory

first second third fourth fifth


element element element element element

8
Arrays (Terminology)

 In the definition:
int [ ] tests;
tests = new int[ISIZE];

 int is the data type of the array elements


 tests is the name of the array
 ISIZE, in [ISIZE], is the size declarator. It shows the number
of elements in the array.
 The size of an array is the number of bytes allocated for it

(number of elements) * (bytes needed for each element)

9
Arrays (Terminology) (cont…)

Array Terminology Examples The Length of an Array

Once an array is created, its


size is fixed. It cannot be
changed. You can find its size
using

arrayRefVar.length

,For example

myList.length //returns
10

10
Arrays (Accessing Array Elements)

Subscripts
(index) 0 1 2 3 4

11
Arrays (Example)

{ public class Test After the array is created

{ public static void main(String[] args) 0 0


1 0
;int[] values = new int[5]
2 0

{ for (int i = 1; i < 5; i++) 3 0

4 0
;values[i] = i + values[i-1]

} After the first iteration

;values[0] = values[1] + values[4] 0 0

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…)

 The following algorithm gives an example of finding the average of elements


in array whose elements are reals.

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

 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

 A linked structure is introduced to overcome limitations of


arrays and allow easy insertion and deletion

17
Introduction (cont.)

 A linked structure is introduced to overcome limitations of


arrays and allow easy insertion and deletion
 A collection of nodes storing data items and links to other nodes
 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
 Nodes can be located anywhere in the memory
 The first node is called head and the last node is called tail

18
Linked Structures

 An alternative to array-based implementations are linked structures


 A linked structure uses object references to create links between
objects
 Recall that an object reference variable holds the address of an
object

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…)

 Each node contains at least

1. A piece of data (any type)

2. Pointer to the next node in the list


 head : pointer to the first node
 Sometimes called front, first

 The last node points to NULL

node

A
data pointer
21
Variations of Linked Lists

 Linked list can be Singly-Linked or Doubly-Linked

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…)

 Circular linked lists


 The last node points to the first node of the list

A B C
Head

 How do we know when we have finished traversing the


list? (Tip: check if the pointer of the current node is
equal to the head.)
24
Variations of Linked Lists (cont…)

 Circular linked lists


list

2 8 3 5
Circular singly linked list

list
5 2 8 3
Circular doubly linked list

25
Singly Linked Lists

 A singly linked list is a concrete


data structure consisting of a
next
sequence of nodes
 Each node stores
 element node
element
 link to the next node

A B C D
26
Singly Linked Lists - Insertion

We can add a node anywhere into the


list:
1.Empty List
2.Before head
3.After tail
4.In between

27
Insertion (Cases)

Case 1 : Empty List Case


When list is empty, which is indicated by (head == NULL)condition,
the insertion is quite simple. Algorithm sets both head and tail to
point to the new node.

28
Insertion (Case)

Case 2 : Add First


In this case, new node is inserted right
before the current head node.

29
Insertion (Case)

Case 2 : Add First

1st Step : Update the next link of a new node, to point to the current head node.

30
Insertion (Case)

Case 2 : Add First

2nd Step : Update head link to point to the new node.

31
Add First(cont…)

Algorithm addFirst(node)

node.next = head // make node point to the old


head, this is also correct when linked list is empty

head = node // make head point to the new node

32
Insertion (Case)

Case 3 : Add Last


In this case, new node is inserted right
after the current tail node.

33
Insertion (Case)

Case 3 : Add Last

1st Step : Update the next link of the current tail


node, to point to the new node.

34
Insertion (Case)

Case 3 : Add Last

2nd Step : Update tail link to point to the new node.

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

tail = node //make tail 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)

Case 4 : General Case


In general case, new node is always
inserted between two nodes, which are
already in the list. Head and tail links are
not updated in this case.

37
Insertion (Case)

Case 4 : General Case

1nd Step : Update link of the new node, to point to the


"next" node.

38
Insertion (Case)

Case 4 : General Case

2st Step : Update link of the "previous" node, to point


to the new node.

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

 The algorithm whose cases we


have described will remove a
node from anywhere within a list
irrespective of whether the node
is the head, etc.

41
Singly Linked List: Deletion
Algorithm

42
Doubly Linked Lists

 A doubly linked list is a concrete data structure


prev next
consisting of a sequence of nodes.
 Each node stores:
 element
 link to the previous node
 link to the next node element node
 Special trailer and header nodes

header nodes/positions trailer

elements
43
Doubly Linked Lists (cont…)

 In the Doubly linked lists:


 Each node points to the successor and the predecessor
 Advantage:

given a node, it is easy to visit its predecessor. Convenient to


traverse lists backwards

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

Inserting at the Head

heade trailer
r

Rom Seattle New


e York
(a) Before the insertion

heade trailer
r

Sydney Rom Seattle New


e York
(b) After the insertion
46
Doubly Linked Lists

Inserting in the Middle

heade trailer
r

Rom Seattle New


e York
(a) Before the insertion

heade trailer
r

Rome Seattl Sydne New


e y York
(b) After the insertion
47
Doubly Linked Lists

Removing at the Tail

heade trailer
r

Rome Seattl Sydne New


e y York
(a) Before the deletion

heade trailer
r

Rom Seattle Sydney


e
(b) After the deletion
48
Doubly Linked Lists

Removing in the Middle

heade trailer
r

Rome Seattl Sydne New


e y York
(a) Before the deletion

heade trailer
r

Rom Seattle New


e York
(b) After the deletion
49
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.

A linked list is a suitable structure if a large number of insertions and deletions


are needed, but searching a linked list is slower that searching an array.
50
JAVA Built-in LinkedList Class

 Java has a LinkedList class defined as part of the Java


collection framework, which is found in the java.util
package.

 So, you simply declare an instance of the LinkedList


class and call member methods as required by your
program to manipulate the linked list.

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

Both are doing the same operation

53
Singly Linked Lists

Insertion at the End (Append)

public void append(Object obj){


Element element = new Element(obj, null);
if(head == null)
head = element;
else
tail.next = element;
tail = element;
}
Complexity is O(1)

54
Singly Linked Lists

Insertion at the Beginning (Prepend)

public void prepend(Object obj) {


Element element = new Element(obj, head);
if(head == null)
tail = element;
head = element;
}
Complexity is O(1)

55
Singly Linked Lists

Insertion Before and After an Element


 we can also define insertAfter or InsertBefore for the Element class to
insert a given object after or before a specific a node respectively:
public void insertBefore(Object obj) {
Element element = new Element(obj, this);
if(this == head) {
head = element;
return;
}
Element previous = head; Complexity is O(n)
while (previous.next != this) {
previous = previous.next;
}
previous.next = element;
}

public void insertAfter(Object obj) {


next = new Element(obj, next);
if(this == tail)
tail = next; Complexity is O(1)
}
56
Singly Linked Lists

Traversal

 To move a reference e from one node to the next:

e = e.next;

 Example: Count the number of nodes in a linked list.

public int countNodes(){


int count = 0;
Element e = head;
while(e != null){
count++;
e = e.next;
}
Complexity is O( n)
return count;
}

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.

public int countNodes(Object obj){


int count = 0;
Element e = head;
while(e != null){
if(e.data.equals(obj))
count++;
Complexity is O(n)
e = e.next;
}
return count;
}

58
Singly Linked Lists

Deletion – Deleting First and Last Element


public void extractFirst() {
if(head == null)
throw new IllegalArgumentException("item not found");
head = head.next;
if(head == null)
tail = null;
} Complexity is O(1)

public void extractLast() {


if(tail == null)
throw new IllegalArgumentException("item not found");
if (head == tail)
head = tail = null;
else {
Element previous = head;
while (previous.next != tail) Complexity is O(n)
previous = previous.next;
previous.next = null;
tail = previous;
}
} 59
Singly Linked Lists

Deletion – Deleting a specific element


 To delete a specific element, we use either the extract method of MyLinkedList
or that of the Element inner class.
public void extract(Object obj) {
Element element = head;
Element previous = null;
while(element != null && ! element.data.equals(obj)) {
previous = element;
element = element.next;
} Complexity is O(n)
if(element == null)
throw new IllegalArgumentException("item not found");
if(element == head)
head = element.next;
else
previous.next = element.next;
if(element == tail)
tail = previous;
}
60
Doubly Linked Lists Analysis

- Complexity Analysis -

Note: some ideas in this section are repeated in another way, or another
representation way

Both are doing the same operation

61
Doubly Linked Lists

Insertion at the End (append)

public void append(Object obj){


Element element = new Element(obj, null, tail);
if(head == null)
head = tail = element;
else {
tail.next = element;
tail = element; Complexity is O(1)
}
}

62
Doubly Linked Lists

Insertion at the Beginning (prepend)


public void prepend(Object obj){
Element element = new Element(obj, head, null);
if(head == null)
head = tail = element;
else {
head.previous = element;
head = element; Complexity is O(1)
}
}

63
Doubly Linked Lists

Insertion Before an Element


 Inserting before the current node (this) that is neither the first nor the last
node:
Element element = new Element(obj, this, this.previous);
this.previous.next = element;
this.previous = element;

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;
} }

 Example: Count the number of nodes in a linked list.


public int countNodes(){
int count = 0;
Element e = head;
while(e != null){
count++;
e = e.next;
} Complexity is O(n)
return count;
}
65
Doubly Linked Lists

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();

int count = 0, sum = 0;


Element e = tail;
while(e != null && count < n){
sum += ((Integer)e.data).intValue();
count++;
e = e.previous;
}
if(count < n)
throw new IllegalArgumentException(“No. of nodes < "+n);
return sum;
} Complexity is O(n)
66
Doubly Linked Lists

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

You might also like