1 Chapter 4 List 、 stack 、 queue Content: list stack queue.

Presentation on theme: "1 Chapter 4 List 、 stack 、 queue Content: list stack queue."— Presentation transcript:

1 Chapter 4 List 、 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: a i denotes a list element n >= 0 is finite list size is n Data 1 Data 2 Data 3 Data n headtail Empty List Sorted list Unsorted list

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.

abstract

6 List ADT template 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 A 0 A 1 … …… … A n-2 A n-1 An …….. Ai …….. A2 A1 LoLo L o +m L o +(i-1)*m L o + （ n-1)*m address value Loc(a)=L o +i*m Given some position in the list

10 Array-Based List Class template // Array-based list class AList : public List { private: int maxSize; // Maximum size of list int listSize; // Actual elem count int fence; // Position of fence Elem* listArray; // Array holding list public: 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(tempfence)cout< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/13/4036019/slides/slide_13.jpg", "name": "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(tempfence)cout<= 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(tempfence)cout<

13 Array-Based List Insert  (n) Figure 4.4

14 Insert //Insert at front of right partition template bool AList ::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 bool AList ::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 // partition template bool AList ::remove(Elem& it) { if (rightLength() == 0) return false; it = listArray[fence]; // Copy Elem for(int i=fence; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/13/4036019/slides/slide_17.jpg", "name": "16 Remove //Remove and return first Elem in right // partition template bool AList ::remove(Elem& it) { if (rightLength() == 0) return false; it = listArray[fence]; // Copy Elem for(int i=fence; i

17 [Exp 4-1] prints screen “China” #include "sj_List.h" #include "sj_Alist.h" #include "iostream.h" void main(void) { sj_AList 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< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/13/4036019/slides/slide_18.jpg", "name": "17 [Exp 4-1] prints screen China #include sj_List.h #include sj_Alist.h #include iostream.h void main(void) { sj_AList 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<

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 &A,sj_AList &B, sj_AList *C) { int ii=0,jj=0,iend,jend,ai,bj; A.setPos(0); B.setPos(0); iend=A.rightLength(); jend=B.rightLength(); while(iiinsert(bj);B.next();jj++; } }

19 [Exp 4-2 ] (cont) while(ii++insert(ai);A.next();} while(jj++insert(bj);B.next();} } void main() { sj_AList la(5); sj_AList lb(10); sj_AList 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. 试用顺序表作为存储结构，变成实现线性表 （ a 0, a 1, a 2, a 3, …,a n-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 SUN... LI tai l head No a header node used WANG... SUN tai l head Using a header node

24 Link Class // Singly-linked list node template 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 Llist; template class Link {friend class Llist ; 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 tail Insert 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 ?

30 Linked List Class (1) // Linked list implementation template class LList: public List { private: Link * head; // Point to list header Link * tail; // Pointer to last Elem Link * fence; // Last element on left int leftcnt; // Size of left int rightcnt; // Size of right void init() // Intialization routine { fence = tail = head = new Link ; 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 anan aiai a1a1 a2a2 a i-1 h fence S x S x Insert/Append fence anan aiai a1a1 a2a2 a i-1 head S

35 Insert/Append (cont) // Insert at front of right partition template bool LList ::insert(const Elem& item) {fence->next= new Link (item, fence->next); if(tail==fence) tail=fence->next; rightcnt++; return true; }

36 Removal

37 Remove (cont) // Remove and return first Elem in right // partition template bool LList ::remove(Elem& it) { if (fence->next == NULL) return false; it = fence->next->element; // Remember val // Remember link node Link * 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 list template bool LList ::append( const Elem& item ) {tail= tail ->next=new Link ( item, NULL ); rightcnt++; return true; } // Move fence one step left; // no change if left is empty template voidLList ::prev() { Link * temp = head; if(fence==head) return; //No prev Elem while(temp->next!=fence) temp=temp->next; fence=temp; leftcnt--; rightcnt++; } Previous Appen d

39 setPos // Set the size of left partition to pos template bool LList ::setPos(int pos) {if((pos rightcnt+leftcnt)) return false; fence=head; for(int i=0;inext; return true; }

40 Print template void LList ::Print()const {Link *temp=head; Cout<<“<”; while(temp!=fence) {cout next->element<<“”; temp=temp->next; } cout<<“|”; while(temp->next!=NULL) {cout 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. 试用单链表作为存储结构，变成实现线性表 （ a 0, a 1, a 2, a 3, …,a n-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. 根据一个结点数据类型为整型的单链表生成两个单链 表，使得第一个单链表中包含原单链表中所有数值为奇 数的结点，使得第一个单链表中包含原单链表中所有数 值为偶数的结点，原单链表保持不变。

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.

49  Comparison of Implementations Array-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 Prev NULL Head Tail

55 Doubly Linked Insert // Insert at front of right partition template bool LList ::insert(const Elem& item) { fence->next = new Link (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; }

57 Doubly Linked Remove // Remove, return first Elem in right part template bool LList ::remove(Elem& it) { if (fence->next == NULL) return false; it = fence->next->element; Link * 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 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 UALdict : public Dictionary {private: AList * list; public: UALdict(int size=DefaultListSize) { list = new AList (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 list template class SAList: protected AList {public: SAList(int size=DefaultListSize) : AList (size) {} ~SAList() {} AList ::clear; bool insert(const Elem& item) {Elem curr; for (setStart();getValue(curr);next()) if(!Compare::lt(curr, item)) break; return AList ::insert(item); }

72 Sorted array-based list(cont) AList ::remove; AList ::setStart; AList ::setEnd; AList ::prev; AList ::next; AList ::leftLength; AList ::rightLength; AList ::setPos; AList ::getValue; AList ::print; };

73 Dictionary implemented with a sorted array-based list template class SALdict : public ictionary {private: SAList * list; public: SALdict(int size=DefaultListSize) {list=new SAList (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 pushpop 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] 2 3 1 0base s[top]=x top=top+1 top 10 25 30 S[4] 2 3 1 0 top base top=top-1 x=s[top] Stack is empty Push 10 (insert) 30 Pop (delete) S[4] 2 3 1 0 Top=0 top Stack is full top=stacksize 10 25 30 40 S[4] 2 3 1 0 top=4 base Main stack operations: underflow overflow

81 Stack ADT STACK ADT ?? // Stack abtract class template 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 implementation private: 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’ top 0 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 * 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 LStack: public Stack { bool push(const Elem& item) { top = new Link (item, top); size++; return true; } }; P base S b S

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 top2 top1 top2 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 ① ② ⑤ ⑦ ⑧ Parameter Current Locale Return Address ③ ⑥ push ④ Current Locale Return Address Current Locale Return Address Parameter pop

90 Example of Stacks App ——expression process baba / a/b+c*d (a) t1+ a/b+c*d t1=a/b (b) d c t1 *+*+ a/b+c*d (c) t3 a/b+c*d t3=t1+t2 (e) t2 t1 + 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 -1 Tail - 1

93 Queue Model Queue Q Del 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 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

Download ppt "1 Chapter 4 List 、 stack 、 queue Content: list stack queue."

Similar presentations