Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linked Lists, Queues, Stacks

Similar presentations


Presentation on theme: "Linked Lists, Queues, Stacks"— Presentation transcript:

1 Linked Lists, Queues, Stacks
Insertion & Searching ArrayList Vs LinkedList Stack concepts, applications, example & contract Queue

2 Linked lists A linked list consists of a sequence of nodes connected by links, plus a header. Each node (except the last) has a successor, and each node (except the first) has a predecessor. Each node contains a single element (object or value), plus links to its successor and/or predecessor. ant bat cat header node element link null link ant bat cat

3 Singly-linked lists A singly-linked list (SLL) consists of a sequence of nodes, connected by links in one direction only. Each SLL node contains a single element, plus a link to the node’s successor (or a null link if the node has no successor). An SLL header contains a link to the SLL’s first node (or a null link if the SLL is empty). pig dog rat cat dog

4 Insertion Problem: Insert a new element at a given point in a linked list. Four cases to consider: insertion in an empty linked list; insertion before the first node of a nonempty linked list; insertion after the last node of a nonempty linked list; insertion between nodes of a nonempty linked list. The insertion algorithm needs links to the new node’s successor and predecessor.

5 SLL insertion (1) SLL insertion algorithm:
To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate.

6 SLL insertion (2) Animation (insertion before first node):
ant bat cat first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. ant bat cat first ins To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. ant bat cat first ins To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. bat cat first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. ant bat cat first ins To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate.

7 SLL insertion (3) Animation (insertion after intermediate node):
dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. eel dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. eel pred ins dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. eel pred ins dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. pred dog fox first To insert elem at a given point in the SLL headed by first: 1. Make ins a link to a newly-created node with element elem and successor null. 2. If the insertion point is before the first node: Set node ins’s successor to first Set first to ins. 3. If the insertion point is after the node pred: Set node ins’s successor to node pred’s successor Set node pred’s successor to ins. 4. Terminate. eel pred ins

8 Searching (1) Problem: Search for a given target value in a linked list. Unsorted SLL linear search algorithm: To find which (if any) node of the SLL headed by first contains an element equal to target: 1. For each node curr in the SLL headed by first, repeat: If target is equal to node curr’s element, terminate with answer curr. 2. Terminate with answer none. DLL linear search is similar, except that we can search from last to first if preferred.

9 Searching (2) Analysis (counting comparisons):
Let n be the SLL’s length. If the search is successful: Average no. of comparisons = n /2 (half the list) If the search is unsuccessful: No. of comparisons = n In either case, time complexity is O(n).

10 ArrayList Vs LinkedList
An arraylist uses an array for internal storage. This means it's fast for random access (e.g. get me element 99), because the array index gets you right to that element. Adding and deleting at the start or middle of the arraylist would be slow, because all the later elements have to copied forward or backward. ArrayList would also give a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements to it.

11 ArrayList Vs LinkedList (2)
A linkedList is made up of a chain of nodes. Linked lists are slow when it comes to random access. Accessing element 99 means you have to traverse either forward from the beginning or backward from the end (depending on whether 99 is less than or greater than half the list size), calling next or previous, until you get to that element. Linked lists are fast for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.

12 linkedList Example import java.util.*;
public class LinkedListDemo { public static void main(String[] args) {   LinkedList<String> myList=new LinkedList<String>();   myList.add("a");   myList.add("b");   myList.add(“c”);   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of the list is " +  myList.size());    myList.addFirst(“d”); System.out.println(“Contents of list is " + myList);   System.out.println(“Size of the list is "  + myList.size());

13 linkedList Example (ctd)
       myList.addLast(“e");   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of list is"  + myList.size());   myList.add(2,“f");   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of list is" + myList.size()); myList.add(1,”g”);   System.out.println(“Contents of list is " + myList);   System.out.println(“size of list is “ + myList.size());  myList.remove(3);   System.out.println(“Contents of list is " + myList);   System.out.println(“Size of list is “ + myList.size());   } }

14 Stack concepts (1) A stack is a last-in-first-out sequence of elements. Elements can added (push) and removed (pop) only at one end (the top of the stack). The depth of stack is the number of elements it contains. An empty stack has depth zero.

15 Stack concepts (2) Illustration (stack of books): Initially:
Moby Dick War & Peace Rob Roy Initially: Moby Dick War & Peace After removing a book: Moby Dick War & Peace Misérables After adding “Misérables”: Moby Dick War & Peace Misérables 2001 After adding “2001”:

16 Stack applications Interpreter (e.g., the Java Virtual Machine)
maintains a stack containing intermediate results during evaluation of complicated expressions also containing arguments and return addresses for method calls and returns. Parser (e.g., a component of the Java compiler) maintains a stack containing symbols encountered during parsing.

17 Example: text-file reversal
A text file is a sequence of (zero or more) lines. To reverse the order of these lines, we must store them in a first- in-last-out sequence. Text-file reversal algorithm: To output the lines of file in reverse order: 1. Make line-stack empty. 2. For each line read from file, repeat: Add line to the top of line-stack. 3. While line-stack is not empty, repeat: Remove a line from the top of line-stack into line Output line. 4. Terminate.

18 Example: bracketing (1)
A phrase is well-bracketed if: for every left bracket, there is a later matching right bracket for every right bracket, there is an earlier matching left bracket the subphrase between a pair of matching brackets is itself well-bracketed. Examples and counter-examples (maths expressions): s  (s – a)  (s – b)  (s – c) (– b + [b2 – 4ac]) / 2a s  (s – a)  (s – b  (s – c) s  (s – a)  s – b)  (s – c) (– b + [b2 – 4ac)] / 2a well-bracketed well-bracketed ill-bracketed ill-bracketed ill-bracketed

19 Example: bracketing (2)
Bracket matching algorithm: checks for matches of (), [] or {}. To test whether phrase is well-bracketed: 1. Make bracket-stack empty. 2. For each symbol sym in phrase (scanning left to right), repeat: If sym is a left bracket: Add sym to the top of bracket-stack If sym is a right bracket: If bracket-stack is empty, terminate with false Remove a bracket from the top of bracket-stack into left If left and sym are not matched brackets, terminate with false. 3. Terminate with true if bracket-stack is empty, or false otherwise.

20 Stack ADT: requirements
It must be possible to make a stack empty. It must be possible to add (‘push’) an element to the top of a stack. It must be possible to remove (‘pop’) the topmost element from a stack. It must be possible to test whether a stack is empty. It should be possible to access the topmost element in a stack without removing it.

21 Stack ADT: contract (1) Possible contract, expressed as a Java interface*: public interface Stack { // Each Stack object is a stack whose elements are objects. /////////////// Accessors /////////////// public boolean empty(); // Return true if and only if this stack is empty. public Object peek(); // Return the element at the top of this stack. * an interface is a data type that requires implementing, it’s a class that contains only abstract methods and/or constants – it provides a specification – from programming 2

22 Stack ADT: contract (2) Possible contract (continued):
///////////// Transformers ///////////// public void clear (); // Make this stack empty. public void push(Object elem); // Add elem as the top element of this stack. public Object pop(); // Remove and return the element at the top of this stack. }

23 Stacks in the Java class library
Java java.util.Stack class does this, but has no clear() function However, the java.util.LinkedList class also provides all the Stack operations clear() is LinkedList clear(), empty() is isEmpty(), peek() is getLast(), push() is addLast(), pop() is removeLast(). import java.util.LinkedList; LinkedList bookStack = new LinkedList(); bookStack.addLast("Moby Dick"); bookStack.addLast("War & Peace"); bookStack.addLast("Rob Roy"); System.out.println(bookStack.removeLast());

24 Queue concepts (1) A queue is a first-in-first-out sequence of elements. Elements can added only at one end (the rear of the queue) and removed only at the other end (the front of the queue). The length of a queue is the number of elements it contains. An empty queue has length zero.

25 Queue concepts (2) Illustration (queue of persons): BUS STOP

26 Queue applications Print server Disk driver
maintains a queue of print jobs. Disk driver maintains a queue of disk input/output requests. Scheduler (e.g., in an operating system) maintains a queue of processes awaiting a slice of machine time. Traffic simulation Maintains many queues of vehicles

27 Example: demerging (1) Consider a file of person records, each of which contains a person’s name, gender, date-of-birth, etc. The records are sorted by date-of-birth. We are required to rearrange the records such that females precede males but they remain sorted by date-of- birth within each gender group. Bad idea: use a sorting algorithm. Time complexity is O(n log n) at best. Good idea: use a demerging algorithm. Time complexity is O(n).

28 Example: demerging (2) Demerging algorithm:
To rearrange a file of person records such that females precede males but their order is otherwise unchanged: 1. Make queues females and males empty. 2. Until the input file is empty, repeat: Let p be the next person read in from the file If p is female, add p to the rear of females If p is male, add p to the rear of males. 3. Until females is empty, repeat: Write out the person removed from the front of females. 4. Until males is empty, repeat: Write out the person removed from the front of males. 5. Terminate.

29 Queue ADT: requirements
It must be possible to make a queue empty. It must be possible to test whether a queue is empty. It must be possible to obtain the length of a queue. It must be possible to add an element at the rear of a queue. It must be possible to remove the front element from a queue. It must be possible to access the front element in a queue without removing it.

30 Queue ADT: contract (1) Possible contract, expressed as a Java interface: public interface Queue { // Each Queue object is a queue whose elements are objects. /////////////// Accessors /////////////// public boolean isEmpty (); // Return true if and only if this queue is empty. public int size (); // Return this queue’s length. public Object getFirst (); // Return the element at the front of this queue.

31 Queue ADT: contract (2) Possible contract (continued):
/////////////// Transformers /////////////// public void clear (); // Make this queue empty. public void addLast (Object elem); // Add elem as the rear element of this queue. public Object removeFirst (); // Remove and return the front element of this queue. }

32 Queue interface public interface Queue<E> extends Collection<E> { E element(); boolean offer(E o); E peek(); E poll(); E remove(); }

33 Queue Interface continued
Each Queue method exists in two forms: one throws an exception if the operation fails the other returns a special value (either null or false, depending on the operation). Queue Interface Structure Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek()

34 Queues in the Java class library
The java.util.LinkedList class provides all the Queue operations, for example import java.util.LinkedList; LinkedList<String> queue = new LinkedList<String>(); queue.addLast("Homer"); queue.addLast("Marge"); queue.addLast("Bart"); queue.addLast("Lisa"); queue.addLast("Maggie"); System.out.println(queue.removeFirst());


Download ppt "Linked Lists, Queues, Stacks"

Similar presentations


Ads by Google