13StacksAndQueues
合集下载
相关主题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Maintain pointer to first node in a linked list; insert/remove from front.
StdIn to StdOut
to null
be
be
first
or
to null
insert at front of linked list
or
be
to null
stack
push pop
queue enqueue dequeue
Stack. Examine the item most recently added. Queue. Examine the item least recently added.
LIFO = "last in first out" FIFO = "first in first out"
push pop
% more tobe.txt to be or not to - be - - that - - - is % java StackOfStrings < tobe.txt to be not that or be
6
Stack: linked-list representation
12
Stack: array implementation
public class FixedCapacityStackOfStrings { private String[] s; private int N = 0;
a cheat (stay tuned)
wenku.baidu.com
public FixedCapacityStackOfStrings(int capacity) { s = new String[capacity]; } public boolean isEmpty() { return N == 0; } public void push(String item) {
10
Stack: linked-list implementation performance
Proposition. Every operation takes constant time in the worst case.
Proposition. A stack with N items uses ~ 40 N bytes.
Warmup client. Reverse sequence of strings from standard input.
5
Stack test client
Read strings from standard input. If string equals "-", pop string from stack and print. Otherwise, push string onto stack.
9
Stack: linked-list implementation in Java
public class LinkedStackOfStrings { private Node first = null; private class Node { String item; Node next; } public boolean isEmpty() { return first == null;
oldfirst first or
be
to null
set the instance variables in the new node
first.item = "not"; first.next = oldfirst;
first not or
be
to null
Inserting a new node at the beginning of a linked list
be
to null
first
or
be
to null
return saved item
return item;
Removing the first node in a linked list
8
Stack push: linked-list implementation
save a link to the list
Client: program using operations defined in interface. Implementation: actual code implementing operations. Interface: description of data type, basic operations.
2
Client, implementation, interface
Separate interface and implementation. Ex: stack, queue, bag, priority queue, symbol table, union-find, .… Benefits. Client can't know details of implementation ⇒ client has many implementation from which to choose. Implementation can't know details of client needs ⇒ many clients can re-use the same implementation. Design: creates modular, reusable libraries. Performance: use optimized implementation where it matters.
3
1.3 B AGS, QUEUES, AND STACKS
‣ stacks ‣ resizing arrays
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
‣ queues ‣ generics ‣ iterators ‣ applications
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
Stacks and queues
Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear when we insert. Which item do we remove?
push(): pop():
add new item at s[N]. remove item from s[N-1].
s[]
to
0
be
1
or
2
not
3
to
4
be
5
null
6
null
7
null
8
null
9
N
capacity = 10
Defect. Stack overflows when N exceeds capacity. [stay tuned]
7
Stack pop: linked-list implementation
save item to return
String item = first.item;
delete first node
inner class
first = first.next;
first or
private class Node { String item; Node next; }
use to index into array; then increment N
s[N++] = item;
}
public String pop() { return s[--N]; } }
Node oldfirst = first;
oldfirst first
or
be
to null
inner class
create a new node for the beginning
private class Node { String item; Node next; }
first = new Node();
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
1.3 B AGS, QUEUES, AND STACKS
‣ stacks ‣ resizing arrays
Algorithms
F O U R T H E D I T I O N
‣ queues ‣ generics ‣ iterators ‣ applications
{ String item; Node next; }
8 bytes (inner class extra overhead) 8 bytes (reference to String)
references
next
8 bytes (reference to Node) 40 bytes per stack node
not
not
or
be
to null
to
to
not
or
be
to null
-
to
not
or
be
remove from front of linked list
to null
be
be
not
or
be
to null
-
be
not
or
be
to null
-
not
or be to null
that
that
or
be
to null
node object (inner class)
public class Node { String item; inner class Node next; ... private class Node }
40 bytes
object overhead extra overhead item
16 bytes (object overhead)
private inner class (access modifiers don't matter)
}
public void push(String item) { Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; } public String pop() { String item = first.item; first = first.next; return item; } }
Remark. This accounts for the memory for the stack (but not the memory for strings themselves, which the client owns).
11
Stack: array implementation
Array implementation of a stack. Use array s[] to store N items on stack.
public static void main(String[] args) { StackOfStrings stack = new StackOfStrings(); while (!StdIn.isEmpty()) { String s = StdIn.readString(); if (s.equals("-")) StdOut.print(stack.pop()); else stack.push(s); } }
Stack API
Warmup API. Stack of strings data type.
push pop
public class StackOfStrings StackOfStrings() void push(String item) String pop() boolean isEmpty() int size() create an empty stack insert a new string onto stack remove and return the string most recently added is the stack empty? number of strings on the stack
StdIn to StdOut
to null
be
be
first
or
to null
insert at front of linked list
or
be
to null
stack
push pop
queue enqueue dequeue
Stack. Examine the item most recently added. Queue. Examine the item least recently added.
LIFO = "last in first out" FIFO = "first in first out"
push pop
% more tobe.txt to be or not to - be - - that - - - is % java StackOfStrings < tobe.txt to be not that or be
6
Stack: linked-list representation
12
Stack: array implementation
public class FixedCapacityStackOfStrings { private String[] s; private int N = 0;
a cheat (stay tuned)
wenku.baidu.com
public FixedCapacityStackOfStrings(int capacity) { s = new String[capacity]; } public boolean isEmpty() { return N == 0; } public void push(String item) {
10
Stack: linked-list implementation performance
Proposition. Every operation takes constant time in the worst case.
Proposition. A stack with N items uses ~ 40 N bytes.
Warmup client. Reverse sequence of strings from standard input.
5
Stack test client
Read strings from standard input. If string equals "-", pop string from stack and print. Otherwise, push string onto stack.
9
Stack: linked-list implementation in Java
public class LinkedStackOfStrings { private Node first = null; private class Node { String item; Node next; } public boolean isEmpty() { return first == null;
oldfirst first or
be
to null
set the instance variables in the new node
first.item = "not"; first.next = oldfirst;
first not or
be
to null
Inserting a new node at the beginning of a linked list
be
to null
first
or
be
to null
return saved item
return item;
Removing the first node in a linked list
8
Stack push: linked-list implementation
save a link to the list
Client: program using operations defined in interface. Implementation: actual code implementing operations. Interface: description of data type, basic operations.
2
Client, implementation, interface
Separate interface and implementation. Ex: stack, queue, bag, priority queue, symbol table, union-find, .… Benefits. Client can't know details of implementation ⇒ client has many implementation from which to choose. Implementation can't know details of client needs ⇒ many clients can re-use the same implementation. Design: creates modular, reusable libraries. Performance: use optimized implementation where it matters.
3
1.3 B AGS, QUEUES, AND STACKS
‣ stacks ‣ resizing arrays
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
‣ queues ‣ generics ‣ iterators ‣ applications
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
Stacks and queues
Fundamental data types. Value: collection of objects. Operations: insert, remove, iterate, test if empty. Intent is clear when we insert. Which item do we remove?
push(): pop():
add new item at s[N]. remove item from s[N-1].
s[]
to
0
be
1
or
2
not
3
to
4
be
5
null
6
null
7
null
8
null
9
N
capacity = 10
Defect. Stack overflows when N exceeds capacity. [stay tuned]
7
Stack pop: linked-list implementation
save item to return
String item = first.item;
delete first node
inner class
first = first.next;
first or
private class Node { String item; Node next; }
use to index into array; then increment N
s[N++] = item;
}
public String pop() { return s[--N]; } }
Node oldfirst = first;
oldfirst first
or
be
to null
inner class
create a new node for the beginning
private class Node { String item; Node next; }
first = new Node();
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
1.3 B AGS, QUEUES, AND STACKS
‣ stacks ‣ resizing arrays
Algorithms
F O U R T H E D I T I O N
‣ queues ‣ generics ‣ iterators ‣ applications
{ String item; Node next; }
8 bytes (inner class extra overhead) 8 bytes (reference to String)
references
next
8 bytes (reference to Node) 40 bytes per stack node
not
not
or
be
to null
to
to
not
or
be
to null
-
to
not
or
be
remove from front of linked list
to null
be
be
not
or
be
to null
-
be
not
or
be
to null
-
not
or be to null
that
that
or
be
to null
node object (inner class)
public class Node { String item; inner class Node next; ... private class Node }
40 bytes
object overhead extra overhead item
16 bytes (object overhead)
private inner class (access modifiers don't matter)
}
public void push(String item) { Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; } public String pop() { String item = first.item; first = first.next; return item; } }
Remark. This accounts for the memory for the stack (but not the memory for strings themselves, which the client owns).
11
Stack: array implementation
Array implementation of a stack. Use array s[] to store N items on stack.
public static void main(String[] args) { StackOfStrings stack = new StackOfStrings(); while (!StdIn.isEmpty()) { String s = StdIn.readString(); if (s.equals("-")) StdOut.print(stack.pop()); else stack.push(s); } }
Stack API
Warmup API. Stack of strings data type.
push pop
public class StackOfStrings StackOfStrings() void push(String item) String pop() boolean isEmpty() int size() create an empty stack insert a new string onto stack remove and return the string most recently added is the stack empty? number of strings on the stack