COMP211slides_4

31
E.G.M. Petrakis lists 1 Lists List: finite sequence of data elements all elements have the same data type The operations depend on the type of the list and not on the data type List: the most general type Ordered: element is ascending order Stacks, Queues: not all operations are allowed

description

δομές αρχείων

Transcript of COMP211slides_4

E.G.M. Petrakis lists 1

Lists

List: finite sequence of data elementsall elements have the same data type

The operations depend on the type of the list and not on the data typeList: the most general type

Ordered: element is ascending orderStacks, Queues: not all operations are allowed

E.G.M. Petrakis lists 2

list orhead

infonext

list

new element

Insertion after currentposition

current rear ortail

E.G.M. Petrakis lists 3

list orhead

list

new element

Insertion at current position

current rear ortail

E.G.M. Petrakis lists 4

list orhead

list orhead

deleted element

Deletion after currentposition

currentrear or

tail

E.G.M. Petrakis lists 5

list orhead

list orhead

deleted element

Deletion at current position

currentrear or

tail

E.G.M. Petrakis lists 6

Terminology

empty: contains no elementslength: number of elements in listhead, or list: pointer to the beginning of the listtail: pointer to the last elementcurrent: pointer to current elementordered: elements in ascending or descending order

E.G.M. Petrakis lists 7

Operations

setFirst: set “current” to “head”setPos(i): sets current to the i-th element currValue: returns value of “current” elementnext/prev: “current” points to next/previous elementclear: delete all elementsinsert: inserts an element at/after current positionappend: inserts an element at “tail”remove: delete the element at/after “current” positionisInList: true/false if current position is in listisEmpty: true/false if list is empty

E.G.M. Petrakis lists 8

ADT Listinterface List { // List ADT in Java

public void clear(); // Remove all Objectspublic void insert(Object item); // Insert at curr pospublic void append(Object item); // Insert at tailpublic Object remove(); // Remove/return currpublic void setFirst(); // Set to first pospublic void next(); // Move to next pospublic void prev(); // Move to prev pospublic int length(); // Return curr lengthpublic void setPos(int pos); // Set curr positionpublic void setValue(Object val); // Set current valuepublic Object currValue(); // Return curr valuepublic boolean isEmpty(); // True if empty listpublic boolean isInList(); // True if in list

} // interface List

E.G.M. Petrakis lists 9

Iteration

Iterate through the whole list : MyListfor (MyList.first( ); MyList.isInList( ); MyList.next( ))

DoSomething(MyList.currValue( ));

If MyList: (12 32 15) and current points to 32 then MyList.insert(90) changes the list to be (12 32 90 15)

E.G.M. Petrakis lists 10

List Implementations

Array-based: very fastthe elements are stored in array static: actual number of elements less than size allocated

Dynamic Memory: slower, more efficientallocates memory for new elementsdynamic: no restriction on number of elements (except memory size)

E.G.M. Petrakis lists 11

Array Implementation (1)

Elements in continuous array positionsHead of list at pos 0Insertion and Deletion cause shifting of elements

E.G.M. Petrakis lists 12

class AList implements List { // Array-based list class

private static final int defaultSize = 10;

private int msize; // Maximum size of listprivate int numInList; // Actual list sizeprivate int curr; // Position of currprivate Object[] listArray; // Array holding list

AList() { setup(defaultSize); } // ConstructorAList(int sz) { setup(sz); } // Constructor

private void setup(int sz) { // Do initializationsmsize = sz;numInList = curr = 0;ListArray = new Object[sz]; // Create listArray

}

public void clear() // Remove all Objects from list{ numInList = curr = 0; } // Simply reinitialize values

E.G.M. Petrakis lists 13

public void insert(Object it) { // Insert at curr posAssert.notFalse(numInList < msize, "List is full");Assert.notFalse((curr >=0) && (curr <= numInList), "Bad value for curr");for (int i=numInList; i>curr; i--) // Shift up

listArray[i] = listArray[i-1];listArray[curr] = it;numInList++; // Increment list size

}

public void append(Object it) { // Insert at tailAssert.notFalse(numInList < msize, "List is full");listArray[numInList++] = it; // Increment list size

}

public Object remove() { // Remove and return ObjectAssert.notFalse(!isEmpty(), "No delete: list empty");Assert.notFalse(isInList(), "No current element");Object it = listArray[curr]; // Hold removed Objectfor (int i=curr; i<numInList-1; i++) // Shift down

listArray[i] = listArray[i+1];numInList--; // Decrement list sizereturn it;

}

E.G.M. Petrakis lists 14

public void setFirst() { curr = 0; } // Set to firstpublic void prev() { curr--; } // Move curr to prevpublic void next() { curr++; } // Move curr to nextpublic int length() { return numInList; }public void setPos(int pos) { curr = pos; }public boolean isEmpty() { return numInList == 0; }

public void setValue(Object it) { // Set current valueAssert.notFalse(isInList(), "No current element");listArray[curr] = it;}

public boolean isInList() // True if curr within list{ return (curr >= 0) && (curr < numInList); }

} // Array-based list implementation

E.G.M. Petrakis lists 15

Array Implementation (2)1 115 26list

0261051211

11189

10111213

nodes

NULL

E.G.M. Petrakis lists 16

313 14 376 5 12List 1

17 26List 2

31 19 32List 3

1 18 13 11 4 15List 4

E.G.M. Petrakis lists 17

1 26 0

2 11 10

3 5 16

4 1 25

5 17 1

6 13 2

7

8 19 19

9 14 13

10 4 22

11

12 31 8

13 6 3

14

15

16 37 24

17 3 12

18

19 32 0

20

21 7 9

22 15 0

23

24 12 0

25 18 6

List 4List 2

List 3

List 1

E.G.M. Petrakis lists 18

class AList implements List { // Array-based list class

private static final int defaultSize = 10;private int msize; // Maximum size of listprivate int numInList; // Actual list sizeprivate int curr; // Position of currprivate int avail; // next available positionprivate Object[] listArray; // Array holding listprivate int[] listarray_next; // array holding pointers to next Object

private void setup(int sz) { // Do initializationsmsize = sz; numinlist = curr = 0;listarray = new Object[sz];listarray_next = new int[sz];avail = 0; // the first available elementfor (i=0; i < msize; i++)

listarray_next[i] = i+1; // each elem points to its successorlistarray_next[msize-1] = nothing; // the last elem has no next

}

E.G.M. Petrakis lists 19

private int get_node( ) { // Get next available nodeif (avail == nothing) // from stack

error(‘list overflow’)else {

int pos = avail;avail = listarray_next[avail];return pos;

}}

private void free_node (int p) { // make node availablelistarray_next[p] = avail; // push node back to stackavail =p;

}

private void insert(int p, Object x) { // insert after node pointed to by “p”if (p < 0 || p >= msize)

error (‘void insertion’)else {

int q = get_node( );listarray[q] = x;listarray_next[q] = listarray_next[p];listarray_next[p] = q;

}}

E.G.M. Petrakis lists 20

private void delete(int p, Object x) {if ( p > 0 || p >= msize) // deletes elem after elem

error (‘void deletion’); // pointed to by “p”else {

int q = listarray_next[p];x = listarray[q];listarray_next[p] = listarray_next[q];free_node(q);

}}public AList() { setup(defaultSize); } // Constructorpublic AList(int sz) { setup(sz); } // Constructor

public void clear( ) {…} // remove all ELEMs from listpublic void insert(Object it) {…} // insert ELEM at current positionpublic void append(Object it) {…} // insert ELEM at tail of listpublic Object remove( ) {…} // remove and return current ELEMpublic void setFirst( ) {…} // set curr to first position;public void prev( ) {…} // move curr to previous position;public void next( ) {…} // move curr to next position;public int length( ) {…} // return current length of list

} // Array-based list implementation

E.G.M. Petrakis lists 21

Dynamic MemoryAllocates memory for new elements as neededEach node is a distinct objectThe node classclass Link { // A linked-list node

private Object element; // Object for this nodeprivate Link next; // Pointer to next nodeLink(Object it, Link nextval) // Constructor{ element = it; next = nextval; }Link(Link nextval) { next = nextval; } // ConstructorLink next() { return next; }Link setNext(Link nextval) { return next = nextval; }Object element() { return element; }Object setElement(Object it) { return element = it; }

}

E.G.M. Petrakis lists 22

class LList implements List { // Linked list classprivate Link head; // Pointer to list headerprivate Link tail; // Pointer to last Object in listprotected Link curr; // Position of current Object

LList(int sz) { setup(); } // ConstructorLList() { setup(); } // Constructorprivate void setup(){ tail = head = curr = new Link(null); }

public void setFirst() { curr = head; }public void next() { if (curr != null) curr = curr.next(); }

public void prev() { // Move to previous positionLink temp = head;if ((curr == null) || (curr == head)) // No prev{ curr = null; return; } // so returnwhile ((temp != null) && (temp.next() != curr))temp = temp.next();curr = temp;

}

E.G.M. Petrakis lists 23

public Object currValue() { // Return current Objectif (!isInList()) return null;return curr.next().element();

}

public boolean isEmpty() // True if list is empty{ return head.next() == null; }

public void insert(Object it) { // Insert Object at current positionAssert.notNull(curr, "No current element");curr.setNext(new Link(it, curr.next()));if (tail == curr) // Appended new Objecttail = curr.next();

}

public Object remove() { // Remove/return curr Objectif (!isInList()) return null;Object it = curr.next().element(); // Remember valueif (tail == curr.next()) tail = curr; // Set tailcurr.setNext(curr.next().next()); // Cut from listreturn it; // Return value

}

E.G.M. Petrakis lists 24

public void append(Object it) // insert Elem at tail of list{ tail.setNext(new Link(it, NULL)); }

public int length( ) { // return current length of listint cnt = 0; for (Link temp = head.next(); temp != NULL; temp = temp.next())

cnt++; // count Elemsreturn cnt;

}

public void setPos(int pos) { // set curr to positioncurr = head; for (int i = 0; (curr != NULL) && (i < pos) i++) curr = curr.next();

}

public void setValue(Object val) { // set current Elem's valueAssert.notFalse(isInList(), "No current element");curr.next().setElement(val);

}

public bool isInList( ) // TRUE if curr is within list{ return (curr != NULL) && (curr.next() != NULL); }

} // Linked list class implementation

E.G.M. Petrakis lists 25

ComparisonArray-Based Lists:

insertion and deletion are Θ(n)prev and direct access are Θ(1)fixed space allocated in advancespace reorganization if the array is fullfaster in most cases

Linked Lists:insertion and deletion are Θ(1)prev and direct access are Θ(n)space grows with number of elementsevery element requires overheadslower

E.G.M. Petrakis lists 26

Doubly Linked List

Allows for direct access to both next and previous elements of the current pointer

insert (delete) operations update both “next” and “prev” pointerseasy implementation

E.G.M. Petrakis lists 27

Doubly linked list nodeclass DLink { // A doubly-linked list node

private Object element; // Object for this node private DLink next; // Ptr to next node DLink prev; // Ptr to previous node DLink(Object it, DLink n, DLink p) // Constr. 1 { element = it; next = n; prev = p; } DLink(DLink n, DLink p) { next = n; prev = p; } // Constr. 2 DLink next() { return next; } DLink setNext(DLink nextval) { return next = nextval; } DLink prev() { return prev; } DLink setPrev(DLink prevval) { return prev = prevval; }Object element() { return element; } Object setElement(Object it) { return element = it; }

}

E.G.M. Petrakis lists 28

Insertion in Doubly Linked Listcurrent

current

E.G.M. Petrakis lists 29

current

current

Deletion in Doubly Linked List

E.G.M. Petrakis lists 30

Insertion curr.setNext(new DLink(it, curr.next(), curr));if (curr.next().next() != null)

curr.next().next().setPrev(curr.next());if (tail == curr) // Appended new Object

tail = curr.next();

E.G.M. Petrakis lists 31

Circular Linked Lists

The next pointer of the last element points to the first element