الجامعة الإسلامية بغزة data structures chapter 3 arrays...

38
بغزةميةسمعة الجا اData Structures Chapter 3 Arrays ,Linked Lists, and Recursion م. أحمد غراب

Upload: others

Post on 30-Mar-2021

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

الجامعة الإسلامية بغزةData Structures

Chapter 3Arrays ,Linked Lists, and Recursion

أحمد غراب.م

Page 2: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

2

Array

• Collection of elements of the same data type, stored in adjacent memory locations

• Creating an array

int[] myArray; //variable declared, not initialized

myArray = new int[5]; //memory allocated for array

A number that specifies the capacity is required

• Initializing an array– Array elements are initialized to their default values when memory for the

array is allocated

– An array can be allocated and initialized in the same statement

int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17};

)77–76; Flanagan, 34Basic Java Programming (Goodrich,

Page 3: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

3

Using Arrays

• The first element in every array has the index 0

• Each element can be accessed by using its index

int[] myArray = new int[5];

myArray[0] = 42;

System.out.println(myArray[0]);//what prints?

System.out.println(myArray[3]);//what prints?

• Every array has a public instance variable named length

• Printing the array elements

for( int i=0; i<myArray.length; ++i )

System.out.println(myArray[i]);

)76; Flanagan, 38–34Basic Java Programming (Goodrich,

Page 4: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

4

Array Bounds

• The compiler does not check array bounds

int[] myArray = new int[5];

System.out.println(myArray[256]); //will compile

• But every access is checked at runtime, and if the index is out of bounds then the output is “undefined” and the error, ArrayIndexOutOfBoundsException is thrown

• Common error:

int[] a = new int[5];

System.out.print( a[5] );

)76; Flanagan, 38–34Basic Java Programming (Goodrich,

Page 5: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

5

Arrays can store eitherprimitive values or objects

• Storing primitive variables in an arrayint[] myArray = new int[5];

myArray[0] = 42;

System.out.println(myArray[0]);//what prints?

• Storing reference variables in an array

)100–96Basic Java Programming (Goodrich,

Page 6: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Why Not Arrays?

• Many limitations arise when using arrays

– Must specify unchangeable size when createdStudent[] rum = new Student[1];

Student[] grp = new Student[variable];rum = new Student[60]; // old rum was lost!grp = rum; // grp now alias to rum’s instance

Page 7: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Why Not Arrays? cont

– Waste memory requiring maximum size for arrayRating[] hertz = new Rating[100000000];

– If we want to keep elements ordered

• Adding element : slow insertion in ordered array

• Removing elements

– slow searching in unordered array

– Gaps

Page 8: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

8

ArrayLists and Arrays

• A Java ArrayList object can be used instead of a Java Array

• The ArrayList is considered to be a “better array”

– Both store elements in a linear sequence

– Both provide access to elements by their “index”

• The ArrayList will automatically grow, adding more memory space for itself whenever it’s needed

)230–222Basic Java Programming (Goodrich,

Page 9: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

9

Using the java.util.ArrayList

• You need to import the libraryimport java.util.ArrayList;

• You need to know how to instantiate an ArrayList objectprivate ArrayList<Card> cards;

cards = new ArrayList<Card>();

• You need to know some of the operationsint size()

boolean isEmpty()

E add(E element) E get(int index)

E set(int index, E element)

E remove(int index)

)159Basic Java Programming (Goodrich,

Name of the class Type of data to be stored in it

Refers to any data type

Allocate the memory

Declare a reference variableUse access

specifier only whenthis is an instance variable

Page 10: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Linked lists are linear sequence of nodes

“Thingy” is definition of “Node”

Each Node contains:

Element reference to data stored in Node

Link to next Node in linked list

Singly Linked List

elem

Node

next

Page 11: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Linked lists are linear sequence of nodes

“Thingy” is definition of “Node”

Each Node contains:

Element reference to data stored in Node

Link to next Node in linked list

Singly Linked List

elem next elem next elem next elem nextNode Node Node Node

Page 12: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

public class Node {private String elem;private Node next;public Node(String e, Node n) {elem = e;next = n;

}public String getElement() { return elem;

}public Node getNext() { return next;

}public void setElement(String newE) {elem = newE;

}public void setNext(Node newNext) {next = newNext;

}

}

1st Node Class (of many)

Page 13: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

public class Node<T> {private T elem;private Node<T> next;public Node(T e, Node<T> n) {elem = e;next = n;

}public T getElement() { return elem;

}public Node<T> getNext() { return next;

}public void setElement(T newE) {elem = newE;

}public void setNext(Node<T> newNext) {next = newNext;

}

}

Generic Node Class

Page 14: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

public class Node<TT> {private TT elem;private Node<T> next;public Node(TT e, Node<TT> n) {elem = e;next = n;

}public TT getElement() { return elem;

}public Node<TT> getNext() { return next;

}public void setElement(TT newE) {elem = newE;

}public void setNext(Node<TT> newNext) {next = newNext;

}

}

Generic Node Class

Page 15: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

public class SList<T> {

private Node<T> head;

private int size;

public SList() {

head = null; // Make an empty list

size = 0;

}

public boolean isEmpty() {

return (head == null);

}

public T getFirstElement() {

// Handle situation when list is emptyreturn head.getElem();

}

}

Singly Linked List

Page 16: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = nsize += 1

elem

elem next elem next elem nextNode Node Node

headsize 3

SLinkedList

Page 17: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = nsize += 1

elem

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

n

Page 18: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = nsize += 1

elem

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

n

Page 19: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = nsize += 1

elem

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

n

Page 20: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = nsize += 1

elem

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

n

Page 21: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = nsize += 1

elem

elem next elem next elem next elem nextNode Node Node Node

headsize 4

SLinkedList

n

Page 22: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Inserting at Head

Algorithm addFirst(elem)Node<T> n = new Node<T>();n.setElement(elem);n.setNext(head);head = n

elem next elem next elem next elem nextNode Node Node Node

headsize 4

SLinkedList

Page 23: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing an Internal Node

Linked list's length equals number of elements

Requires unlinking Node from the linked list

Nothing fancy needed, just adjust previous next link

Node 0nly existed via links, so this does all we need

Page 24: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing an Internal Node

Linked list's length equals number of elements

Requires unlinking Node from the linked list

Nothing fancy needed, just adjust previous next link

Node 0nly existed via links, so this does all we need

elem next elem next elem next elem nextNode Node Node Node

headsize 4

SLinkedList

Page 25: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing an Internal Node

Linked list's length equals number of elements

Requires unlinking Node from the linked list

Nothing fancy needed, just adjust previous next link

Node 0nly existed via links, so this does all we need

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

Page 26: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing an Internal Node

Linked list's length equals number of elements

Requires unlinking Node from the linked list

Nothing fancy needed, just adjust previous next link

Node 0nly existed via links, so this does all we need

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

Page 27: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing an Internal Node

Linked list's length equals number of elements

Requires unlinking Node from the linked list

Nothing fancy needed, just adjust previous next link

Node 0nly existed via links, so this does all we need

elem next elem next elem next elem nextNode Node Node Node

headsize 3

SLinkedList

Page 28: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing an Internal Node

Linked list's length equals number of elements

Requires unlinking Node from the linked list

Nothing fancy needed, just adjust previous next link

Node 0nly existed via links, so this does all we need

elem next elem next elem nextNode Node Node

headsize 3

SLinkedList

Page 29: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing the Head

Resized with each addition or removal

Linked list's head node has nothing to unlink No previous node whose next field to be updated

Instead, just need to advance where head refershead = head.getNext();

elem next elem next elem nextNode Node Node

headsize 3

Page 30: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing the Head

Resized with each addition or removal

Linked list's head node has nothing to unlink No previous node whose next field to be updated

Instead, just need to advance where head refershead = head.getNext();

elem next elem next elem nextNode Node Node

headsize 3

Page 31: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Removing the Head

Resized with each addition or removal

Linked list's head node has nothing to unlink No previous node whose next field to be updated

Instead, just need to advance where head refershead = head.getNext();

elem next elem nextNode Node

headsize 2

Page 32: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

© 2004 Goodrich, Tamassia Linked Lists 32

Doubly Linked ListA doubly linked list is often more convenient! Nodes store: element link to the previous node link to the next node

Special trailer and header nodes

prev next

elem

trailerheader Nodes

elements

node

Page 33: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

© 2004 Goodrich, Tamassia Linked Lists 33

InsertionWe visualize operation insertAfter(p, X), which returns position q

A B X C

A B C

p

A B C

p

X

q

p q

Page 34: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

© 2004 Goodrich, Tamassia Linked Lists 34

Insertion AlgorithmAlgorithm insertAfter(p,e):

Create a new node v

v.setElement(e)

v.setPrev(p) {link v to its predecessor}

v.setNext(p.getNext()) {link v to its successor}

(p.getNext()).setPrev(v) {link p’s old successor to v}

p.setNext(v) {link p to its new successor, v}

return v {the position for the element e}

Page 35: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

© 2004 Goodrich, Tamassia Linked Lists 35

DeletionWe visualize remove(p), where p == last()

A B C D

p

A B C

D

p

A B C

Page 36: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

© 2004 Goodrich, Tamassia Linked Lists 36

Deletion Algorithm

Algorithm remove(p):t = p.element {a temporary variable to hold the

return value}(p.getPrev()).setNext(p.getNext()) {linking out p}(p.getNext()).setPrev(p.getPrev())p.setPrev(null) {invalidating the position p}p.setNext(null)return t

Page 37: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

© 2004 Goodrich, Tamassia 37

Doubly-Linked Liststart

Given a pointer to a node in a doubly-linked list, we can remove the node in ( 1 ) time.

This isn’t possible in a singly-linked list, since we must have a pointer to the node in front of the one we want to remove.

Page 38: الجامعة الإسلامية بغزة Data Structures Chapter 3 Arrays ...site.iugaza.edu.ps/ysarraj/wp-content/uploads/file/aghorab/My Class.pdfArrays ,Linked Lists, and Recursion

Dale Roberts

SummarySummary

Types of linked lists:Types of linked lists:Singly linked listSingly linked list

Begins with a pointer to the first nodeBegins with a pointer to the first node

Terminates with a null pointerTerminates with a null pointer

Only traversed in one directionOnly traversed in one direction

Circular, singly linkedCircular, singly linkedPointer in the last node pointsPointer in the last node points

back to the first nodeback to the first node

Doubly linked listDoubly linked listTwo “start pointers” Two “start pointers” –– first element and last elementfirst element and last element

Each node has a forward pointer and a backward pointerEach node has a forward pointer and a backward pointer

Allows traversals both forwards and backwardsAllows traversals both forwards and backwards

Circular, doubly linked listCircular, doubly linked listForward pointer of the last node points to the first node and Forward pointer of the last node points to the first node and backward pointer of the first node points to the last nodebackward pointer of the first node points to the last node