Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1

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

3 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

4 3 List Operations ----What operations should we implement? L = (a,b,c,d,e) Setnull () Prior () Next () Insert( 2,h) Remove( 3) get ( 4 )

5 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.

6 abstract

7 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;

8 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; };

9 8  Array-Based List list physical implementation array-based list linked list

10 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

11 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; }

12 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; }

13 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<

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

15 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

16 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)

17 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

18 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<

19 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++; } }

20 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);

21 20 [Exp 4-2 ] (cont) la.print(); cout<<"\n"; lb.print(); cout<<"\n"; mergelist(la,lb,&lc); lc.print(); cout<<"\n"; }

22 21  Homework1 1. 试用顺序表作为存储结构,变成实现线性表 ( a 0, a 1, a 2, a 3, …,a n-1 )就地逆置的操作。 2. 设顺序表 L 是一个递增有序表。试用顺序表作 为存储结构,编程实现将 x 插入 L 表中,并使 L 仍是一个有序表。 3. 利用顺序表,实现统计在一个输入字符串中 各个不同字符出现的频度。

23 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.

24 23 dn ^ WANG SUN... LI tai l head No a header node used WANG... SUN tai l head Using a header node

25 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

26 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

27 26 List Model head tail Insert an item to a list S->next=P->next P->next=S P

28 27 Delete an item in a list head tail List Model P->next=P->next->next ->next

29 28 Linked List Position (1) previous point ?

30 29 Linked List Position (2)

31 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; }

32 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&);

33 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

34 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; }

35 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

36 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; }

37 36 Removal

38 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; }

39 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

40 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; }

41 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”; }

42 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

43 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

44 43  Homework2 1. 试用单链表作为存储结构,变成实现线性表 ( a 0, a 1, a 2, a 3, …,a n-1 )就地逆置的操作。 2. 设单链表 L 是一个递增有序表。试用顺序表作 为存储结构,编程实现将 x 插入 L 表中,并使 L 仍是一个有序表。 3. 利用单链表,实现统计在一个输入字符串中 各个不同字符出现的频度。

45 44 Homework2 ( cont ) 4. 已知 L1 和 L2 分别指向两个单链表的头结点,且已知 其长度分别为 m 和 n 。试编程实现将这两个链表连接在 一起。 5. 设 A 和 B 是两个单链表,其表中元素递增有序。试编 程将 A 和 B 归并成一个按元素值递增有序的单链表 C 。 6. 设有一个表头指针为 h 的单链表。试设计一个算法, 通过遍历一趟链表,将链表中所有结点的链接方向逆转。 要求逆转结果链表的头指针 h 指向原链表的最后一个结 点。 7. 根据一个结点数据类型为整型的单链表生成两个单链 表,使得第一个单链表中包含原单链表中所有数值为奇 数的结点,使得第一个单链表中包含原单链表中所有数 值为偶数的结点,原单链表保持不变。

46 45 Head Tail Circularly Linked List

47 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.

48 47 The Link Class With a Freelist --System new and delete are slow // Singly-linked list node with freelist template class Link { private: static Link * freelist ; // Head public: 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 };

49 48 The Link Class With a Freelist (cont) template Link * Link ::freelist = NULL; template // Overload for new void* Link ::operator new(size_t) { if (freelist == NULL) return ::new Link; Link * temp = freelist; // Reuse freelist = freelist->next; return temp; // Return the link } template // Overload delete void Link ::operator delete(void* ptr) {((Link *)ptr)->next = freelist; freelist = (Link *)ptr; }

50 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.

51 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.

52 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.

53 52 Doubly Linked List Data Next Prev Data Next Prev Data Next Prev NULL Head Tail

54 53 Doubly Linked Lists Simplify insertion and deletion: Add a prev pointer. // Doubly-linked list link node template 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; } };

55 54 Doubly Linked Insert

56 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 56 Doubly Linked Remove

58 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; }

59 58  Homework3 1. 设计一个实现下述要求的定位函数 Locate() 。 设有一个带表头结点的双向链表 L ,每个结点有 4 个 数据成员:前驱指针 prev 、后继指针 next 、数据 Data 和访问频度 freq 。所有节点的 freq 初始值都为 0 。每当 在链表上进行依次 locate(L,x) 操作时,令元素值为 x 的 结点的访问频度 freq 加 1 ,并将该结点前移,连接到与 它的访问频度相等的结点后面,使得链表中所有的结 点保持按访问频度递减的顺序排列,以使频繁被访问 的结点总是靠近表头。 Locate

60 59 Homework3 ( cont ) 2. 利用双向循环链表的操作,解决约瑟夫问题。 Josephus question : 设 n 个人围成一个圆圈,按一指定方向,从第 s 个人开始报数,报数到 m 为止,报数为 m 的人 出列,然后,从下一个开始重新报数,报数到 m 的人又出列, … ,直到所有的人全部出列为止。 Josephus question 要对任意给定的 n 、 s 和 m ,求按出列次序得到的人员顺序表。 Josephus

61 60 Homework3 ( cont ) 3. 集合运算。 由集合运算的定义知,( A-B )∪( B-A ) 的结果是 A 与 B 的非公共部分所构成的集合。 Sets

62 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

63 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; };

64 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

65 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; } };

66 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; } };

67 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;} };

68 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; }

69 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; }

70 69 Unsorted List Dictionary (cont) bool removeAny(Elem& e) {if (size() == 0) return false; list->setEnd(); list->prev(); list->remove(e); return true; }

71 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(); } };

72 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); }

73 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; };

74 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; }

75 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; }

76 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();

77 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(); } };

78 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.

79 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.

80 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

81 80 10 S[4] base s[top]=x top=top+1 top S[4] top base top=top-1 x=s[top] Stack is empty Push 10 (insert) 30 Pop (delete) S[4] Top=0 top Stack is full top=stacksize S[4] top=4 base Main stack operations: underflow overflow

82 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; };

83 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

84 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; } } ┋

85 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

86 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

87 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.

88 87 Applications of Stacks top1 top2 top1 top2 Two stacks implemented within in a single array,both growing toward the middle

89 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

90 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

91 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)

92 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

93 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

94 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

95 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; };

96 95 Queue Implementation (1)

97 96 Queue Implementation (2)

98 97

99 98


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

Similar presentations


Ads by Google