Title: Stack and Queue Using Linked Lists
1Stack and QueueUsing Linked Lists
1
UWP - Qi Yang
2Stack Upside-Down
8 7 6 5 4 3 2 1 0
top
3Implementing Stack Using Array
- public class Stack
-
- private Object items
- private int top 0
- public Stack( int size )
-
- items new Objectsize
-
- public void push ( Object obj )
-
- itemstop obj
-
- public Object pop()
-
- return items--top
-
- . . .
-
4Implementing Stack Using Linked List
- The signatures of the methods should stay the
same - The implementation shouldn't matter to the user
as long as it is correct and efficient - Should "top" be the front or back?
- Whats the Big O for pop and push?
- if top is front
- O(1)
- if top is back
- O(n)
- So top should be front!
5- Top is front
- push insert at front
- top new Node(obj, top)
- pop remove from front
- top top.next
. . .
. . .
top
. . .
top
5
5
6Implementing Stack Using Linked List
- public class Stack
-
- Node top
- public Stack()
-
- top null
-
- public void push ( Object obj )
-
- top new Node(obj, top)
-
- public Object pop()
-
- Object tmp top.info
- top top.next
- return tmp
-
- . . .
-
7Queue Class
front points to where the first element is
rear points to where next element goes
8public class Queue private Object items
private int front, rear, count ...
public void add ( Object x )
itemsrear x rear (rear 1)
items.length count public
Object remove() Object x
itemsfront front (front 1)
items.length count -- return x
// class Queue
9Queue Using a Linked List
- Two pointers front and rear
- Both add and remove are O(1).
- Note we make class Node private, so no access
outside the class. - Make the Queue generic it doesnt get the
warnings that the generic array implementation
gave
. . .
front
10- public class QueueltEgt
-
- // treat as a dumb struct, but private to
Queue - private class Node
-
- public E info
- public Node next
- public Node ( E x, Node p )
-
- info x
- next p
-
-
- Â private Node front rear null
- public boolean isEmpty()
-
- return front null
-
- Â . . .
10
10
11- add (at rear)
- rear.next new Node ( x, null )
- rear rear.next
- remove (at front)
- tmp front.info
- front front.next
. . .
front
tmp
. . .
front
11
11
12- public class QueueltEgt
-
- Â . . .
- public void add ( E x ) // add at the end
-
- if ( front null )
-
- front new Node ( x, null )
- rear front
-
- else
-
- rear.next new Node ( x, null )
- rear rear.next
-
- Â
- public E remove() // remove from the front
-
- if ( front null )
12
12
13Quiz 5
14Quiz 6
- Hashing
- Division (remainder)
- Collision
- Linear Probe
- Double hash
- Buckets
- Binary Search
- Linked List
- Add and remove
15Prog6
- Inheritance
- Polymorphysm
- Class PFigure
- Move
- Other methods
-
16Lab 8