תרגול 12: ומחסניתIteratorרשימה מקושרת, תור, 1. רשימה מקושרת...

Post on 21-Dec-2015

228 views 0 download

Transcript of תרגול 12: ומחסניתIteratorרשימה מקושרת, תור, 1. רשימה מקושרת...

12תרגול :

,רשימה מקושרת, תורIteratorומחסנית

1

(Linked Listרשימה מקושרת )

רשימה מקושרת הינה קבוצה סדורה של אובייקטים, כאשר כל אובייקט ברשימה מכיל הצבעה לאובייקט הבא. כל אובייקט מהווה חוליה בשרשרת:

  Link - קודקוד ברשימה הינו מסוג

LinkedList- כל הרשימה נקראת

null

Data NextLink

2

Linkמחלקה שמייצגת חוליה

Data NextLink

3

public class Link {private Object data;private Link next;

public Link(Object data, Link next) {this.data = data;this.next = next;

}public Link(Object data) {

this(data, null);}public Object getData() {

return data;}public void setData(Object data) {

this.data = data;}public Link getNext() {

return next;}public void setNext(Link next) {

this.next = next;}

}

LinkedListמחלקה שמייצגת רשימה משורשרת

public class LinkedList {private Link first;

 public LinkedList (){

first = null;}

 public LinkedList (Object data){

first = new Link(data, null);}

  ...

}

4

LinkedListמחלקה שמייצגת רשימה משורשרת

null

LinkedList

data next data next data next

first

5

public boolean isEmpty() {return (first == null);

}

:נוסיף למחלקה את השיטה

?נרצה לדעת האם הרשימה שלנו מכילה איברים או לא אם trueאשר תחזיר )( isEmpty אז נוסיף את השיטה הבוליאנית

אחרת.falseהרשימה ריקה, ו-

6

נוסיף למחלקה את השיטה:

7

public void addLast(Object data) {Link newLink = new Link(data, null);if (isEmpty()) {

first = newLink;}else {

Link linkPointer = first;while (linkPointer.getNext() != null) {

linkPointer = linkPointer.getNext();}linkPointer.setNext(newLink);

}}

דוגמת שימוש

lst.addLast( "World!");

LinkedList lst = new LinkedList();

lst.addLast( "Hello" );

lst.addLast( "Great" );

nulldata next data next data next

LinkedListfirst

null

8

נוסיף שיטה אשר מסירה את החוליה הראשונה ברשימהומחזירה את האובייקט המוצבע על ידה.

public Object removeFirst(){ Object ans;

if (isEmpty()) {ans = null;

}else {

ans = first.getData();first = first.getNext();

}return ans;

}

:נוסיף גם למחלקה את השיטה

9

המשך דוגמת שימוש

lst.removeFirst();

lst.removeFirst();

lst.removeFirst();

nulldata next data next data next

LinkedListfirst

"Hello" "Great" "World!"10

המשך דוגמת שימוש

lst.removeFirst();

nulldata next data next

LinkedListfirst

lst.removeFirst();

lst.removeFirst();

"Great" "World!"11

המשך דוגמת שימוש

lst.removeFirst();

nulldata next

LinkedListfirst

lst.removeFirst();

lst.removeFirst();

"World!"12

המשך דוגמת שימוש

lst.removeFirst();

null

LinkedListfirst

lst.removeFirst();

lst.removeFirst();

13

: getMiddle את השיטהLinkedListנוסיף למחלקה

.1getMiddle

- מהו האיבר האמצעי ברשימה?

- רעיונות לפתרון?

14

getMiddle

15

public Object getMiddle(){Object ans;if(isEmpty()) {

ans = null; }else {

Link current = first;Link jumper = first;while( (jumper != null) &&

(jumper.getNext() != null) ){current = current.getNext();jumper = jumper.getNext().getNext();

}ans = current.getData();

}return ans;

}

&&

… while( (jumper != null) && (jumper.getNext() != null) ){ current = current.getNext(); jumper = jumper.getNext().getNext(); } ans = current.getData(); …

16

את LinkedListנוסיף למחלקה : containsCirclesהשיטה

2 .containsCircles

– האם יש מעגלים ברשימה?

- האם עלולים להיווצר מעגלים שכאלה?

- חידה: כמה מעגלים לכל היותר יכולים להיות ברשימהמקושרת?

17

18

public boolean containsCircles(){

boolean ans;if(isEmpty()) {

ans = false;}else {

Link current = first;Link jumper = first;boolean start = true;while(jumper != null && ( current != jumper || start) ){

start = false;current = current.getNext();jumper = jumper.getNext();if (jumper != null)

jumper = jumper.getNext();}ans = (jumper != null);

}return ans;

}

while)jumper != null && ) current != jumper || start( ({start = false;current = current.getNext)(;jumper = jumper.getNext)(;if )jumper != null(

jumper = jumper.getNext)(;}

19

while)jumper != null && ) current != jumper || start( ({start = false;current = current.getNext)(;jumper = jumper.getNext)(;if )jumper != null(

jumper = jumper.getNext)(;}

20

while)jumper != null && ) current != jumper || start( ({start = false;current = current.getNext)(;jumper = jumper.getNext)(;if )jumper != null(

jumper = jumper.getNext)(;}

21

while)jumper != null && ) current != jumper || start( ({start = false;current = current.getNext)(;jumper = jumper.getNext)(;if )jumper != null(

jumper = jumper.getNext)(;}

22

while)jumper != null && ) current != jumper || start( ({start = false;current = current.getNext)(;jumper = jumper.getNext)(;if )jumper != null(

jumper = jumper.getNext)(;}

23

while)jumper != null && ) current != jumper || start( ({start = false;current = current.getNext)(;jumper = jumper.getNext)(;if )jumper != null(

jumper = jumper.getNext)(;}

24

Iterator

25

Iterator

( הדרושים לתכנית מחשב dataמידע ונתונים )•(. data structure )מבנה נתוניםנשמרים בתוך

על מבנה נתונים יש צורך לבצע מספר פעולות, •.כמו הכנסת נתונים והוצאת נתונים

אחת הדרכים להוציא נתונים היא לעבור על •.אוסף הנתונים פריט-מידע אחר פריט-מידע

26

Iteratorנרצה שתכונה זו תהיה משותפת למבני נתונים רבים, •

.למשל לרשימה, שראינו זה עתה.יממשלכן נגדיר ממשק, שאותו כל מבנה נתונים •ניתן למעבר נרצה להגיד שמבנה נתונים הוא •

JAVA. ב-Iterable, ובאנגלית: פריט-אחר-פריט

קיים הממשק:

27

public interface Iterable { /** * Returns an iterator over a set of elements. * * @return an Iterator. */ Iterator iterator();}

Iterator

יהיה לנו אובייקט שיעזור בתהליך. אובייקט זה •יעבור על אוסף הנתונים פריט אחר פריט, לפי

. Iteratorסדר מסוים, ובאנגלית:

מוגדר ממשק לעבודה עם אובייקט כזה:JAVAב-

28

public interface Iterator {/** * Returns true if the iteration has more elements. * @return true if the iterator has more elements. */boolean hasNext();

/** * Returns the next element in the iteration. * @return the next element in the iteration. * @exception NoSuchElementException iteration has no more elements. */Object next();

/** * Removes from the underlying collection the last element returned by the * iterator (optional operation) * @exception UnsupportedOperationException if the "remove" * operation is not supported by this Iterator. * * @exception IllegalStateException if the "next" method has not * yet been called, or the "remove" method has already * been called after the last call to the "next" * method. */void remove();

}

29

Iteratorשימוש ב-, Iterator כך שתתמוך ב-LinkedListבהמשך נראה כיצד להפוך את המחלקה

Iteratorכרגע נניח שהמחלקה כבר תומכת בו, ועל סמך זאת נעשה שימוש ב- מממשת את LinkedList, שמובטחת לנו מכיוון ש-)(iteratorשמתקבל מהשיטה

Iterable.

30

public static void main(String[] args) {LinkedList lst = new LinkedList();lst.addLast("Shnitsels");lst.addLast(“Are");lst.addLast("Tasty");

Iterator it = lst.iterator();while (it.hasNext()) {

Object currentData = it.next();System.out.print(currentData);if (it.hasNext())

System.out.print(", ");}System.out.println();

}

ListIteratorcurrentLink

דוגמת שימוש

data next data next

LinkedListfirst

31data next null

while (it.hasNext()) {Object currentData = it.next();System.out.print(currentData);if (it.hasNext())

System.out.print(", ");}System.out.println();

Shnitsels, Are, Tasty

LinkedList במחלקה Iteratorמימוש ה-

במחלקה Iteratorעתה נראה כיצד נתמוך ב LinkedList:

ListIteratorראשית נגדיר את המחלקה •: Iteratorשמממשת את הממשק

32

LinkedList במחלקה Iteratorמימוש ה-public class ListIterator implements Iterator {

private Link currentLink;

public ListIterator(Link first) { currentLink = first;

}public boolean hasNext() {

return ( currentLink != null );}

public Object next() {if (!hasNext()) {

throw new NoSuchElementException();}Object data = currentLink.getData();currentLink = currentLink.getNext();return data;

}public void remove() {

throw new UnsupportedOperationException();}

} 33

LinkedList במחלקה Iterableמימוש ה-

עכשיו כל מה שנותר לעשות הוא לממש את • ב Iterable של הממשק )(iteratorהשיטה

LinkedList:public class LinkedList implements Iterable{

private Link first;public LinkedList (){

first = null;}… // All methods remain the same

public Iterator iterator(){return new ListIterator(first);

}}

34

הערות• Iterator מניח שלא נעשה שינוי באוסף עליו הוא עובר

. אם נעשה שינוי – האיטרטור איננו במהלך המעברבמצב חוקי ואין הבטחה לפעולה תקינה שלו.

מחוייבת לזרוק את החריגה next השיטה )(•NoSuchElementException במידה ואין יותר אלמנטים

נוודא ש )(nextבאוסף. ) אם לפני כל קריאה ל-hasNext)( החזיר true.)אז לא נתקל בחריגה זו

נזרקת UnsupportedOperationExceptionהחריגה: •כאשר אנו מחוייבים להכריז שיטה מסויימת )למשל כי

היא חלק מממשק( במחלקה שלנו, אך אנו לא תומכים בשיטה זו. לכן בגוף השיטה נזרוק את החריגה.

35

filterהשיטה לסינון איברים העונים על תנאי מתוך כלל איברי

הרשימה.

עתה נתכנן שיטה לסינון איברי הרשימה. נשאיר רק איברים העונים על תנאי כלשהו.

אך מהו התנאי? קשה לקבוע תנאי שכן רשימה היא מבנה נתונים כללי היכול להכיל •

איברים מסוגים שונים. 

36

filterהשיטה לסינון איברים העונים על תנאי מתוך כלל איברי

הרשימה.

אז מה נעשה?

, המקבלת accept המכיל שיטה אחת והיא Filter נגדיר ממשק •אובייקט ומחליטה האם הוא עובר את הסינון או לא.

:Filterראשית נגדיר את הממשק •

37

public interface Filter {/** * accept – defines the filtration criterion. * @param o the object to be examined. * @return true if the object should not be * filtered out. */public boolean accept(Object o);

}

, המשאיר רק את המחרוזות הלא String פשוט עבור המחלקה Filterאנו נממש ריקות:

public class EmptyStringFilter implements Filter {public boolean accept(Object o) {

boolean ans = false;if (o instanceof String) {

String s = (String) o;ans = s.length() > 0;

}return ans;

} }

 38

, המקבלת מסנן LinkedList היינו רוצים לממש שיטה במחלקה ומחזירה רשימה מסוננת.

כך שנוכל להשתמש בה באופן הבא:

LinkedList lst = new LinkedList(); lst.addLast( "Hello" ); lst.addLast( "" ); lst.addLast( "" ); lst.addLast( "Great" ); lst.addLast( "" ); lst.addLast( "World" );  LinkedList ans =

lst.filter(new EmptyStringFilter()); //ans = ["Hello" , "Great" , "World" ]

39

public LinkedList filter(Filter filter) {LinkedList filteredList = new LinkedList() ;Iterator it = this.iterator(); while (it.hasNext()) {

Object data = it.next();if(filter.accept(data)) {

filteredList.addLast(data) ;}

}return filteredList;

}

:LinkedListכל שנותר הוא לממש את אלגוריתם הסינון ב-האלגוריתם מקבל כקלט מסנן, ומחזיר רשימה חדשה שתכיל את כל

.אברי הרשימה הנוכחית שעברו את המסנן

40

LinkedList lst = new LinkedList(); lst.addLast( "Hello" ); lst.addLast( "" ); lst.addLast( "" ); lst.addLast( "Great" ); lst.addLast( "" ); lst.addLast( "World" );  LinkedList ans =

lst.filter(new EmptyStringFilter()); //ans = ["Hello" , "Great" , "World" ]

41

Queueתור -

הוא מבנה נתונים (Queue) תור •המזכיר תור של בני אדם: האיבר

שנכנס ראשון לתור- יוצא ממנו ראשון. 2ניתן לראות כקופסה סגורה בעלת •

פתחים: פתח הכנסה ופתח יציאה. FIFOאיבר שנכנס ראשון יוצא ראשון •

(FIFO - First In First Out) .שימושים: ניהל תהליכים ע"י מערכת •

ההפעלה, ניהול תור בבית מרקחת, ...

42

public interface Queue{ /** * isEmpty - checks if the queue is empty or not. * @return true if the queue is empty */ public boolean isEmpty(); /** * dequeue - removes an object from the head of the queue. * (FIFO order) * @return the next object in the queue. */ public Object dequeue(); /** * enqueue - inserts an object into the queue. * @param o the object to be enqueued. */ public void enqueue(Object o);}

43

מימוש תור ע"י רשימה מקושרתpublic class QueueAsList implements Queue {

private LinkedList lst;

 

public QueueAsList() { lst = new LinkedList(); }

 

public boolean isEmpty() {

return lst.isEmpty();

}

 

public Object dequeue() {

return lst.removeFirst();

}

  public void enqueue(Object o) {

lst.addLast(o);

}

}

44

דוגמה

נרצה לקלוט מהמשתמש מספר מחרוזות ורק

כאשר הוא יסיים להקליד )למשל ע"י זיהוי שורה

ריקה( נדפיס בחזרה את כל המחרוזות בדיוק לפי

סדר ההכנסה.

45

המשךimport java.util.Scanner;…public static void main(String args[]) {

Scanner sc = new Scanner(System.in);Queue q = new QueueAsList();

System.out.println("Insert few lines … ");

while (sc.hasNextLine()) {String line = sc.nextLine();q.enqueue( line );

}

System.out.println("Printing all the lines back! ");

while (!q.isEmpty()) {System.out.println(q.dequeue());

}}

46

:"WIMBELDONדוגמה נוספת "'

רוצים לבצע טורניר טניס

47

המשך נרצה לממש את השיטה:

public static Player simulateTournament(LinkedList playersList)

אשר מקבלת רשימה של שחקנים ומבצעת סימולציה של טורניר טניס באופן הבא:

* בשלב הראשון השחקנים מתחלקים לזוגות.

* מכל זוג עולה המנצח לשלב הבא ושוב השחקנים

מתחלקים לזוגות עד שנותר שחקן בודד שהוא

המנצח )טורניר נוק אוט(.

48

נממש את השיטה ע"י שימוש בתור – כאשר

נאתחל אותו באברי הרשימה, וכל עוד התור מכיל

יותר מאיבר אחד נשלוף שני שחקנים מהתור, "ניתן"

להם לשחק ואת המנצח נכניס לסוף התור )עבר לסיבוב הבא(.

המשך

49

שחקן 1

שחקן 2

שחקן 3

שחקן 4שחקן 4

שלב 1:

המשך

שחקן 1

שחקן 2

שחקן 3

שחקן 450

שחקן 1

שחקן 2

שחקן 3

4שחקן

שחקן 2

שחקן 4

שלב 1:

שלב 2:

המשך

שחקן 2

שחקן 451

שחקן 3

שחקן 1

שחקן 2

שחקן 3

4שחקן

שחקן 2

4שחקן

שחקן 4

שחקן 4

שלב 1:

שלב 2:

המשך

שחקן 2

שחקן 452

שחקן 1

שחקן 2

שחקן 3

4שחקן

שחקן 2

4שחקן

2שחקן

שחקן 4

שחקן 4

שלב 1:

שלב 2:

3שלב :)המנצח(

המשך

שחקן 253

public static Player simulateTournament( LinkedList playersList) {

Queue q = new QueueAsList();Iterator it = playersList.iterator();Player winner = null;while (it.hasNext()) {

q.enqueue( it.next() );}while ( ! q.isEmpty() ) {

Player first = (Player)q.dequeue();if (q.isEmpty()) {

winner = first;} else {

Player second = (Player)q.dequeue();Player matchWinner = getWinner(first,second);q.enqueue( matchWinner );

}}return winner;

}

54

( stack )מחסנית

( היא מבנה נתונים שמזכיר stack )מחסנית•מחסנית של רובה: האיבר שנכנס ראשון למחסנית

(.LIFO - Last In First Outיוצא ממנה אחרון )ניתן לראות במחסנית קופסה סגורה בעלת פתח •

יחיד, שדרכו נעשות פעולות הדחיפה והשליפה.הטיפול דרך פתח יחיד יוצר מצב שבו איבר שנכנס •

. LIFOאחרון יוצא ראשון- מחסנית היא שימושית כאשר יש צורך•

לשמור נתונים בסדר מסוים ולשלוף אותם בסדר הפוך.

55

public interface Stack {/** * push - adds an element to the stack. * @param o the elemented to be inserted to the stack. */

public void push (Object o); /** * pop - removes an element form the stack (LIFO order). * @return the element from the top of the stack. */ public Object pop (); /** * isEmpty - checks if the stack is empty or not. * @return true if there is no more elements in the stack. */ public boolean isEmpty();}

ממשק

56

s ומחזירה העתק של המחסנית s מקבלת כארגומנט מחסנית copyהשיטה זהה.sכאשר יש לשמור על סדר האיברים במחסנית המועתקת וב-

דוגמה – העתק מחסנית

public static Stack copy(Stack s){ Stack temp = new StackImpl();Stack ans = new StackImpl();while (!s.isEmpty()) {

temp.push(s.pop());}while (!temp.isEmpty()) {

Object o = temp.pop();ans.push(o);s.push(o);

}return ans;

}

57