الجامعة الإسلامية بغزة data structures chapter 3 arrays...
TRANSCRIPT
الجامعة الإسلامية بغزةData Structures
Chapter 3Arrays ,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,
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,
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,
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,
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
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
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,
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
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
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
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)
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
© 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
© 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
© 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}
© 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
© 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
© 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.
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