1 Chapter 4 List 、 stack 、 queue Content: • list • stack • queue
1
Chapter 4List 、 stack 、 queue
Content:
• list
• stack
• queue
2
Lists
A list is a finite, ordered sequence of data elements.
Important concept: List elements have a position.
Notation:
<a0, a1, …, an-1>
< >
ai denotes a list elementn >= 0 is finitelist size is n
Data 1 Data 1 Data 2 Data 2 Data 3 Data 3 Data n Data n
head tailEmpty List
Sorted list
<1,3,5,6,8,9,21,24,56,77>
<98,65,43,23,11,10,9,6,5,4,2>
Unsorted list
<1,6,3,9,34,30,19,8,12,44>
3
List Operations----What operations should we
implement?
L = (a,b,c,d,e)• Setnull ()• Prior ()• Next ()• Insert( 2,h)• Remove( 3)• get ( 4 )
4
current position and fence
Our list implementation will support the concept of a current position.
We will do this by defining the list in terms of left and right partitions.
• Either or both partitions may be empty.
Partitions are separated by the fence.
<20, 23 | 12, 15> <20, 23 | 10,12, 15>
abstract
6
List ADTtemplate <class Elem> class List {public: virtual void clear() = 0; virtual bool insert(const Elem&) = 0; virtual bool append(const Elem&) = 0; virtual bool remove(Elem&) = 0; virtual void setStart() = 0; virtual void setEnd() = 0;
7
List ADT (cont)
virtual void prev() = 0; virtual void next() = 0; virtual int leftLength()const = 0; virtual int rightLength()const = 0; virtual bool setPos(int pos)= 0; virtual bool getValue(Elem&)const = 0;
virtual void print() const = 0;};
8
Array-Based List
list physical implementation
array-based list linked list
9
Array-Based List (cont)
element element
A0 A1 … …… … An-2 An-1 A0 A1 … …… … An-2 An-1
An
……..
Ai
……..
A2
A1Lo
Lo+m
Lo+(i-1)*m
Lo+ ( n-1)*m
address value
Loc(a)=Lo+i*m
Given some position in the list
10
Array-Based List Classtemplate <class Elem> // Array-based listclass AList : public List<Elem> {private: int maxSize; // Maximum size of list int listSize; // Actual elem count int fence; // Position of fence Elem* listArray; // Array holding listpublic: AList(int size=DefaultListSize) { maxSize = size; listSize = fence = 0; listArray = new Elem[maxSize]; } ~AList() { delete [] listArray; }
11
Array-Based List Class (2)void clear() { delete [] listArray; listSize = fence = 0; listArray = new Elem[maxSize];}Bool insert(const Elem&);Bool append(const Elem&);Bool remove(Elem&);void setStart() { fence = 0; }void setEnd() { fence = listSize; }void prev() { if (fence != 0) fence--; }void next() { if (fence <= listSize) fence++; }int leftLength() const { return fence; }int rightLength() const { return listSize - fence; }
12
Array-Based List Class (3)bool setPos(int pos) { if ((pos >= 0) && (pos <= listSize)) fence = pos; return (pos >= 0) && (pos <= listSize);
}
bool getValue(Elem& it) const { if (rightLength() == 0) return false; else { it = listArray[fence]; return true; }}Void print()const{ int temp=0; Cout<<“<”; while(temp<fence)cout<<listArray [temp++]<<“ ”; cout<<“|”; while(temp>fence)cout<<listArray [temp++]<<“ ”; cout<<“>\n”;}}
Most of the other member functions for class
alist simply access the current list element or
move the position of the fence.such operations
all require (1) time.
13
Array-Based List Insert
(n)
Figure 4.4
14
Insert//Insert at front of right partitiontemplate <class Elem>bool AList<Elem>::insert(const Elem& item) {
if (listSize == maxSize) return false;
for(int i=listSize; i>fence; i--) // Shift Elems up to make room listArray[i] = listArray[i-1]; listArray[fence] = item; listSize++; // Increment list size return true; }
fence
15
Append// Append Elem to end of the list
template <class Elem>
bool AList<Elem>::append(const Elem& item)
{
if(listSize==maxSize)return false;
listArray[listSize++]=item;
return true;
}
fence
(n)
16
Remove//Remove and return first Elem in right// partitiontemplate <class Elem>bool AList<Elem>::remove(Elem& it) { if (rightLength() == 0) return false; it = listArray[fence]; // Copy Elem for(int i=fence; i<listSize-1; i++) // Shift them down listArray[i] = listArray[i+1]; listSize--; // Decrement size return true; }
17
[Exp 4-1] prints screen “China”#include "sj_List.h"#include "sj_Alist.h"#include "iostream.h"void main(void){ sj_AList<char> l1(10); char ch; l1.insert('C'); l1.insert('h'); l1.insert('i'); l1.insert('n'); l1.insert('a'); l1.setPos(4); for(int i=0;i<5;i++) { l1.getValue(ch);cout<<ch; l1.prev(); } cout<<"\n"; l1.print(); cout<<"\n";}
18
[Exp 4-2] merges A and B
sorted list descend
#include "sj_List.h"#include "sj_Alist.h"#include "iostream.h"void mergelist(sj_Alist<int> &A,sj_AList<int> &B, sj_AList<int> *C){ int ii=0,jj=0,iend,jend,ai,bj; A.setPos(0); B.setPos(0); iend=A.rightLength(); jend=B.rightLength(); while(ii<iend&&jj<jend) { A.getValue(ai); B.getValue(bj);
if(ai<bj){C->insert(ai); A.next();ii++; } else{C->insert(bj);B.next();jj++; } }
19
[Exp 4-2 ] (cont) while(ii++<iend)
{A.getValue(ai);C->insert(ai);A.next();} while(jj++<jend)
{B.getValue(bj);C->insert(bj);B.next();}}void main(){ sj_AList<int> la(5); sj_AList<int> lb(10); sj_AList<int> lc(15); for(int i=9;i>0;i=i-2) la.insert(i); for(int j=18;j>=2;j=j-2) lb.insert(j);
20
[Exp 4-2 ] (cont)
la.print();
cout<<"\n";
lb.print();
cout<<"\n";
mergelist(la,lb,&lc);
lc.print();
cout<<"\n";}
21
Homework1
1. 试用顺序表作为存储结构,变成实现线性表( a0, a1, a2, a3, …,an-1 )就地逆置的操作。 2. 设顺序表 L 是一个递增有序表。试用顺序表作为存储结构,编程实现将 x 插入 L 表中,并使 L 仍是一个有序表。 3. 利用顺序表,实现统计在一个输入字符串中各个不同字符出现的频度。
22
Linked List ----What is linked list? • A series of data items: a1, a2, a3, a4, …
• Each data item has a link to the next one.
• Two pointers are required. One for the head of the list and another for the tail of the list
• In a list, which is a kind of data type, the operation includes: add/remove from two ends of the list, insert/delete in the middle of the list.
23
dn ^WANG SUNSUN ... LI LI
tail
headNo a header node used
WANG ... SUN SUN
tailhead
Using a header node
24
Link Class
// Singly-linked list nodetemplate <class Elem> class Link {public: Elem element; // Value for this node Link *next; // Pointer to next node Link(const Elem& elemval, Link* nextval =NULL) { element=elemval; next=nextval; } Link(Link* nextval =NULL) { next = nextval; }};
Dynamic allocation of new list elements
element next
25
template <class Elem> class Llist;template <class Elem> class Link{friend class Llist<Elem>; private: Elem element; // Value for this node Link *next; // Pointer to next node public: Link(const Elem& elemval,Link* nextval=NULL)
{ element=elemval; next=nextval; }
Link(Link* nextval =NULL) { next = nextval; }};
Link Class
26
List Model
head
tailInsert an item to a list
S->next=P->next P->next=S
P
27
Delete an item in a list
head tail
List Model
P->next=P->next->next ->next
28
Linked List Position (1)
previous point ?
29
Linked List Position (2)
30
Linked List Class (1)// Linked list implementationtemplate <class Elem> class LList:
public List<Elem> {private: Link<Elem>* head; // Point to list header Link<Elem>* tail; // Pointer to last Elem Link<Elem>* fence;// Last element on left
int leftcnt; // Size of left int rightcnt; // Size of right void init() // Intialization routine { fence = tail = head = new Link<Elem>; leftcnt = rightcnt = 0; }
31
Linked List Class (2)void removeall() // Return link nodes to { free store
while(head != NULL) { fence = head; head = head->next; delete fence; } }public: LList(int size=DefaultListSize){ init(); }
~LList() { removeall(); } // Destructor void clear() { removeall(); init(); }Bool insert(const Elem&);Bool append(const Elem&);Bool remove(Elem&);
32
Linked List Class (3)
void setStart() { fence = head;
rightcnt += leftcnt;leftcnt = 0; }
void setEnd() { fence = tail;
leftcnt += rightcnt;rightcnt = 0; }
Void prev();
Bool setPos(int pos);
void next()
{if(fence!=tail){fence=fence->next;
rightcnt--; leftcnt++; }
}
Don't move fence if
right empty
33
Linked List Class (4)
int leftLength() const { return leftcnt; }int rightLength() const { return rightcnt; }bool getValue(Elem& it) const { if(rightLength() == 0) return false; it = fence->next->element; return true; }Void print()const;}
34
anai
a1 a2
ai-1
h
fence
S xS x
Insert/Append
fence anai
a1 a2
ai-1
head
S
35
Insert/Append (cont)
// Insert at front of right partitiontemplate<class Elem>bool LList<Elem> ::insert(const Elem& item) {fence->next= new Link<Elem>(item, fence->next);
if(tail==fence) tail=fence->next; rightcnt++; return true;}
36
Removal
37
Remove (cont)
// Remove and return first Elem in right// partitiontemplate <class Elem> bool LList<Elem>::remove(Elem& it) {
if (fence->next == NULL) return false; it = fence->next->element; // Remember val // Remember link node Link<Elem>* ltemp = fence->next; fence->next = ltemp->next; // Remove if (tail == ltemp) // Reset tail tail = fence; delete ltemp; // Reclaim space rightcnt--; return true;}
38
//Append Elem to end of the listtemplate <class Elem> bool LList<Elem>::append(const Elem& item){tail=tail->next=new Link<Elem>(item,NULL); rightcnt++; return true;}// Move fence one step left;// no change if left is emptytemplate <class Elem> voidLList<Elem>::prev() { Link<Elem>* temp = head; if(fence==head) return; //No prev Elem while(temp->next!=fence) temp=temp->next; fence=temp; leftcnt--; rightcnt++;}
Previous
Append
39
setPos// Set the size of left partition to pos
template <class Elem>bool LList<Elem>::setPos(int pos) {if((pos<0)||(pos>rightcnt+leftcnt)) return false; fence=head; for(int i=0;i<pos;i++) fence=fence->next; return true;}
40
Printtemplate <class Elem>void LList<Elem>::Print()const {Link<Elem>*temp=head; Cout<<“<”; while(temp!=fence) {cout<<temp->next->element<<“”; temp=temp->next; } cout<<“|”; while(temp->next!=NULL) {cout<<temp->next->element<<“”; temp=temp->next; } cout<<“>\n”;}
41
[Exp 4-3] Programming:
inserts five numbers of the
integer to empty linked list,
and sums up all elements of
this list. Exp4-3.cpp
42
[Exp 4-4]
Programming a function of Locate:
Finds i’th node in linked list– success:
print the address and the value
of i’th node– unsuccess :
return NULL
Locate:
Exp4-4
43
Homework2
1. 试用单链表作为存储结构,变成实现线性表( a0, a1, a2, a3, …,an-1 )就地逆置的操作。 2. 设单链表 L 是一个递增有序表。试用顺序表作为存储结构,编程实现将 x 插入 L 表中,并使 L 仍是一个有序表。 3. 利用单链表,实现统计在一个输入字符串中各个不同字符出现的频度。
44
Homework2 ( cont )4. 已知 L1 和 L2 分别指向两个单链表的头结点,且已知其长度分别为 m 和 n 。试编程实现将这两个链表连接在一起。5. 设 A 和 B 是两个单链表,其表中元素递增有序。试编程将 A 和 B 归并成一个按元素值递增有序的单链表 C 。6. 设有一个表头指针为 h 的单链表。试设计一个算法,通过遍历一趟链表,将链表中所有结点的链接方向逆转。要求逆转结果链表的头指针 h 指向原链表的最后一个结点。7. 根据一个结点数据类型为整型的单链表生成两个单链表,使得第一个单链表中包含原单链表中所有数值为奇数的结点,使得第一个单链表中包含原单链表中所有数值为偶数的结点,原单链表保持不变。
45
Head Tail
Circularly Linked List
46
Freelists
• A freelist holds those list nodes that are not currently being used
• When a new element is to be added to a linked list,the freelist is checked to see if a list node is available.
• Instead of making repeated calls to new and delete,the link class can handle its own freelist.
47
The Link Class With a Freelist--System new and delete are slow
// Singly-linked list node with freelisttemplate <class Elem> class Link {private:
static Link<Elem>* freelist; // Headpublic: Elem element; // Value for this node Link* next; // Point to next node Link(const Elem& elemval,Link* nextval=NULL)
{ element=elemval; next=nextval; } Link(Link* nextval=NULL) {next=nextval;}
void* operator new(size_t); // Overload void operator delete(void*); // Overload};
48
The Link Class With a Freelist (cont)template <class Elem>Link<Elem>* Link<Elem>::freelist = NULL;template <class Elem> // Overload for newvoid* Link<Elem>::operator new(size_t) { if (freelist == NULL) return ::new Link; Link<Elem>* temp = freelist; // Reuse freelist = freelist->next; return temp; // Return the link}template <class Elem> // Overload deletevoid Link<Elem>::operator delete(void* ptr){((Link<Elem>*)ptr)->next = freelist; freelist = (Link<Elem>*)ptr;}
49
Comparison of ImplementationsArray-Based Lists:• Insertion and deletion are (n).• Prev and direct access are (1).• Array must be allocated in advance.• No overhead if all array positions are
full.
Linked Lists:• Insertion and deletion are (1).• Prev and direct access are (n).• Space grows with number of elements.• Every element requires overhead.
50
Space Comparison
“ Break-even” point:
DE = n(P + E);
n = DE P + E
E: Space for data value.P: Space for pointer.D: Number of elements in array.
51
Doubly Linked Lists
A doubly linked list is
designed to allow
convenient access from a
list node to the next node
and also to the preceding
node on the list.
52
Doubly Linked List
Data
Next
Prev
Data
Next
Prev
Data
Next
PrevNULL
NULL
HeadTail
53
Doubly Linked ListsSimplify insertion and deletion: Add a prev pointer.
// Doubly-linked list link nodetemplate <class Elem> class Link {public: Elem element; // Value for this node Link *next; // Pointer to next node Link *prev; // Pointer to previous node Link(const Elem& e, Link* prevp =NULL, Link* nextp =NULL) { element=e; prev=prevp; next=nextp; } Link(Link* prevp =NULL, Link* nextp =NULL) { prev = prevp; next = nextp; }};
54
Doubly Linked Insert
55
Doubly Linked Insert
// Insert at front of right partitiontemplate <class Elem>bool LList<Elem>::insert(const Elem& item) { fence->next = new Link<Elem>(item, fence, fence->next); if (fence->next->next != NULL) fence->next->next->prev = fence->next; if (tail == fence) // Appending new Elem tail = fence->next; // so set tail rightcnt++; // Added to right return true;}
56
Doubly Linked Remove
57
Doubly Linked Remove// Remove, return first Elem in right parttemplate <class Elem>bool LList<Elem>::remove(Elem& it) { if (fence->next == NULL) return false; it = fence->next->element; Link<Elem>* ltemp = fence->next; if (ltemp->next != NULL) ltemp->next->prev = fence; else tail = fence; // Reset tail fence->next = ltemp->next; // Remove delete ltemp; // Reclaim space
rightcnt--; // Removed from right return true;}
58
Homework3
1. 设计一个实现下述要求的定位函数 Locate() 。
设有一个带表头结点的双向链表 L ,每个结点有 4个数据成员:前驱指针 prev 、后继指针 next 、数据Data 和访问频度 freq 。所有节点的 freq 初始值都为0 。每当在链表上进行依次 locate(L,x) 操作时,令元素值为 x 的结点的访问频度 freq 加 1 ,并将该结点前移,连接到与它的访问频度相等的结点后面,使得链表中所有的结点保持按访问频度递减的顺序排列,以使频繁被访问的结点总是靠近表头。
Locate
59
Homework3 ( cont )
2. 利用双向循环链表的操作,解决约瑟夫问题。
Josephus question : 设 n 个人围成一个圆圈,按一指定方向,从第s 个人开始报数,报数到 m 为止,报数为 m 的人出列,然后,从下一个开始重新报数,报数到 m的人又出列,…,直到所有的人全部出列为止。
Josephus question 要对任意给定的 n 、 s 和m ,求按出列次序得到的人员顺序表。
Josephus
60
Homework3 ( cont )
3. 集合运算。 由集合运算的定义知,( A-B ∪) ( B-A )的结果是 A 与 B 的非公共部分所构成的集合。
Sets
61
Dictionary
Often want to insert records, delete records, search for records.
Required concepts:• Search key: Describe what we are
looking for• Key comparison
– Equality: sequential search– Relative order: sorting
• Record comparison
62
Dictionary ADT
// The Dictionary abstract class.template <class Key, class Elem, class KEComp, class EEComp>class Dictionary {public: virtual void clear()=0; virtual bool insert(const Elem&)=0; virtual bool remove(const Key&,Elem&)=0; virtual bool removeAny(Elem&)=0; virtual bool find(const Key&,Elem&)const=0; virtual int size()=0;};
63
Comparator Class
How do we generalize comparison?• Use ==, <=, >=: Disastrous• Overload ==, <=, >=: Disastrous• Define a function with a standard name
– Implied obligation– Breaks down with multiple key
fields/indices for same object• Pass in a function
– Explicit obligation– Function parameter– Template parameter
64
Comparator Example
class intintCompare {public: static bool lt(int x, int y) { return x < y; } static bool eq(int x, int y) { return x == y; } static bool gt(int x, int y) { return x > y; }};
65
Comparator Example (cont)
class Payroll { public: int ID; char* name;};class IDCompare {public: static bool lt(Payroll& x, Payroll& y) { return x.ID < y.ID; } static bool eq(Payroll& x, Payroll& y) { return x.ID == y.ID; } static bool gt(Payroll& x, Payroll& y) { return x.ID > y.ID; }};
66
Comparator Example (cont)
class NameCompare
{public:
static bool lt(Payroll& x,Payroll& y)
{return strcmp(x.name,y.name)<0;}
static bool eq(Payroll& x,Payroll& y)
{return strcmp(x.name,y.name)==0;}
static bool gt(Payroll& x,Payroll& y)
{return strcmp(x.name,y.name)>0;}
};
67
Unsorted List Dictionary
#include "dictionary.h"
template <class Key, class Elem, class KEComp, class EEComp>
class UALdict : public Dictionary<Key,Elem,KEComp,EEComp>
{private:
AList<Elem>* list;
public:
UALdict(int size=DefaultListSize)
{ list = new AList<Elem>(size); }
~UALdict() { delete list; }
68
Unsorted List Dictionary (cont)
void clear() { list->clear(); }
bool insert(const Elem& e)
{ return list->append(e); }
bool remove(const Key& K, Elem& e)
{for(list->setStart();
list->getValue(e);list->next())
if (KEComp::eq(K, e))
{list->remove(e); return true; }
return false;
}
69
Unsorted List Dictionary (cont)
bool removeAny(Elem& e)
{if (size() == 0) return false;
list->setEnd(); list->prev();
list->remove(e); return true;
}
70
Unsorted List Dictionary (cont)
bool find(const Key& K,Elem& e)const { for(list->setStart(); list->getValue(e);list->next()) if (KEComp::eq(K,e))return true; return false; } int size() {return list->leftLength() +list->rightLength(); }};
71
Sorted array-based listtemplate <class Elem, class Compare>class SAList: protected AList<Elem> {public: SAList(int size=DefaultListSize) : AList<Elem>(size) {} ~SAList() {} AList<Elem>::clear; bool insert(const Elem& item) {Elem curr; for (setStart();getValue(curr);next()) if(!Compare::lt(curr, item)) break; return AList<Elem>::insert(item); }
72
Sorted array-based list(cont)
AList<Elem>::remove; AList<Elem>::setStart; AList<Elem>::setEnd; AList<Elem>::prev; AList<Elem>::next; AList<Elem>::leftLength; AList<Elem>::rightLength; AList<Elem>::setPos; AList<Elem>::getValue; AList<Elem>::print;};
73
Dictionary implemented with a sorted array-based
listtemplate <class Key, class Elem, class KEComp, class EEComp> class SALdict : public ictionary<Key,Elem,KEComp,EEComp>
{private:
SAList<Elem, EEComp>* list;
public:
SALdict(int size=DefaultListSize)
{list=new SAList<Elem, EEComp>(size);}
~SALdict() { delete list; }
74
Dictionary implemented with a sorted array-based
list(cont) void clear() { list->clear(); } bool insert(const Elem& e) { return list->insert(e); } bool remove(const Key& K, Elem& e) {for (list->setStart(); list->getValue(e); list->next()) if(KEComp::eq(K, e)) {list->remove(e);return true;} return false; }
75
Dictionary implemented with a sorted array-based
list(cont)bool removeAny(Elem& e){if(size()==0) return false; list->setEnd(); list->prev(); list->remove(e);return true;}bool find(const Key& K, Elem& e) const{int l=-1; int r=list->leftLength() +list->rightLength();
76
Dictionary implemented with a sorted array-based
list(cont) while (l+1 != r) {int i = (l+r)/2; list->setPos(i);list->getValue(e); if (KEComp::lt(K,e)) r=i; if (KEComp::eq(K,e)) return true; if (KEComp::gt(K, e)) l = i; } return false; } int size() { return list->leftLength() + list->rightLength(); }};
77
Stacks---- What is stack?
• A stack is a list with the restriction that
insertions and deletions can be
performed in only one position. The end
of the list is called the top. The
fundamental operations on a stack are
push = insert, and pop = delete.
78
Stacks (cont)
LIFO: Last In, First Out.
Restricted form of list: Insert and remove only at front of list.
Notation:
• Insert: PUSH
• Remove: POP
• The accessible element is called TOP.
79
Stack Model
A
B
….
MM
push pop
top
bottom
1.Operations:
• Top: get the pointer
• Pop: delete data
• Push: insert data
2.Features of Stack:
• Last -In- First–Out
• Only one pointer
80
10
S[4]
23
10 ba
ses[top]=xtop=top+1
top
10
25
30
S[4]
23
10
top
base top=top-
1x=s[top]
Stack is
empty
Push 10
(insert)
30 Pop
(delete)
S[4]
23
10
Top=0
top
Stack is full
top=stacksize
10
25
30
40S[4]
23
10
top=4
base
Main stack operations:
underflow overflow
81
Stack ADT
STACK ADT ??
// Stack abtract classtemplate <class Elem> class Stack {public: virtual void clear() = 0; virtual bool push(const Elem&) = 0; virtual bool pop(Elem&) = 0; virtual bool topValue(Elem&) const = 0; virtual int length() const = 0;};
82
Array-Based Stack// Array-based stack implementationprivate: int size; // Maximum size of stack int top; // Index for top element Elem *listArray;//Array holding elements
Issues:• Which end is the top?• Where does “top” point to?• What is the cost of the operations?
‘a’ ‘b’ ‘g’ ‘3’ ‘f’
top0 1 2 3 4 5
83
Array-Based Stack(cont) ┋Bool push(const Elem & item)
{ if(top==size)return false;
else {listArray[top++]=item;
return true; }
}
Bool pop( Elem & it)
{ if(top==0)return false;
else {it=listArray[--top];
return true; }
} ┋
84
private:
Link<Elem>* top; //Pointer to first elem
int size; //Count number of elems
• What is the cost of the operations?• How do space requirements compare to the
array-based stack implementation?
Linked Stack
top
Linked stack implementation
85
#include "link.h"#include "stack.h"template <class Elem> class LStack: public Stack<Elem> { bool push(const Elem& item) { top = new Link<Elem>(item, top); size++; return true; }
};
P
base
S
bS
86
Comparison of array-based and linked stack
• Time: Both take constant time.
• Space:
– The array-based stack must declare a fixed-size array initially,and some of that space is wasted whenever the stack is not full.
– The linked stack can shrink and grow but requires the overhead of a link field for every element.
87
Applications of Stacks
top1 top2top1top1top1top1 top2top2top2
Two stacks implemented within in a single array,both growing toward the middle
88
Applications of Stacks
• Direct applications
– Page-visited history in a Web browser
– Undo sequence in a text editor
– Chain of method calls in the Java Virtual Machine
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
89
Example of Stacks App——a function call
MAIN{ }
CALL fun(parameter)
END
fun(parameter)
return
① ②
⑤
⑦⑧
ParameterCurrent LocaleReturn Address
③
⑥
push④
Current Locale
Return Address
Current Locale Return Address
Parameter
pop
pop
90
Example of Stacks App——expression process
ba /
a/b+c*d
(a)
t1 +
a/b+c*d
t1=a/b
(b)
dct1
*+
a/b+c*d
(c)
t3
a/b+c*d
t3=t1+t2
(e)
t2t1 +
a/b+c*d
t2=c*d
(d)
91
Queues
FIFO: First in, First Out
Restricted form of list: Insert at one end, remove from the other.
Notation:
• Insert: Enqueue
• Delete: Dequeue
• First element: Front
• Last element: Rear
92
What is Queue?
• A series of data items, with the addition at the tail and deletion at the head
• Two pointers are required. One for the head of the list and another for the tail of the list
Head -1Tail - 1
93
Queue Model
Queue QDel Q(S)Add Q (x, Q)
x
Features of Queue:1. First-in-first–out (FIFO)2. Two pointers
94
Abstract queue class
template <class Elem> class Queue {public: virtual void clear() = 0; virtual bool enqueue(const Elem&) = 0; virtual bool dequeue(Elem&) = 0; virtual bool frontValue(Elem&) const = 0; virtual int length() const = 0;};
95
Queue Implementation (1)
96
Queue Implementation (2)
97
98