Presentation is loading. Please wait.

Presentation is loading. Please wait.

DATA STRUCTURE Instructor: Dai Min Instructor: Dai Min Office: XNA602 Office: XNA602 Fall 2006.

Similar presentations


Presentation on theme: "DATA STRUCTURE Instructor: Dai Min Instructor: Dai Min Office: XNA602 Office: XNA602 Fall 2006."— Presentation transcript:

1 DATA STRUCTURE Instructor: Dai Min Instructor: Dai Min Office: XNA602 Office: XNA602 Fall 2006

2 课程代码: School of Computer Science &Technology 2 CHAPTER 2 List, Stacks and Queues Abstract Data Types (ADTs) Linear List  Array-based List  Linked List Stacks and Applications Queues and Applications

3 课程代码: School of Computer Science &Technology Abstract Data Type Data Type A data type is a collection of objects and a set of operations that act on those objects.  e.g. in C: int [-32768, ]  Legal operations on integers: + - * /... Abstract Data Type An Abstract Data Type (ADT) is a data type together with the operations, whose properties are specified independently of any particular implementation.

4 课程代码: School of Computer Science &Technology 4 Example:Abstract data type Natural_Number ADT NaturalNumber { objects: an ordered subrange of the integers starting at zero and } NaturalNumber ending at the maximum integer (INT_MAX) on the computer functions: for all x, y  Nat_Number; TRUE, FALSE  Boolean and where +, -, <, and == are the usual integer operations. Int Zero ( ) ::= 0 Boolean Is_Zero(x) ::= if (x) return FALSE else return TRUE int Add(x, y) ::= if ((x+y) <= INT_MAX) return x+y else return INT_MAX Boolean Equal(x,y) ::= if (x== y) return TRUE else return FALSE int Successor(x) ::= if (x == INT_MAX) return x else return x+1 int Subtract(x,y) ::= if (x

5 课程代码: School of Computer Science &Technology 5 Logical vs. Physical Form Data items have both a logical and a physical form. Logical form: definition of the data item within an ADT.  Ex: Integers in mathematical sense: +, - Physical form: implementation of the data item within a data structure.  Ex: 16/32 bit integers, overflow.

6 课程代码: School of Computer Science &Technology Linear List 1 ) Definition : finite same data type. 1 ) Definition : A list is a finite sequence of data elements from the same data type. L = (a 1 a 2 a n ) Notation: L = (a 1, a 2, …, a n ) name name a 1 , a n a 1 is the list head , a n is the last element n n is the length of the list. If n=0, we call the list an empty list. a i-1 a i a i-1 is the directly predecessor of a i a i+1 a i a i+1 is the directly successor of a i

7 课程代码: School of Computer Science &Technology 7 A list is a data structure where data is represented linearly. For a List (not empty) one and only  There is one and only “ head ” element one and only  There is one and only “ last ” element one and only one  Except the list head, every element has one and only one directly predecessor. one and only one  Except the last element, every element has one and only one directly successor.

8 课程代码: School of Computer Science &Technology 8 2 ) ADT of List ADT List { ADT List { Objects: D = { a i | a i ∈ ElemSet, i=1,2,...,n, n≥0 } Objects: D = { a i | a i ∈ ElemSet, i=1,2,...,n, n≥0 } Function: R1 = { | a i-1,a i ∈ D, i=2,...,n } Function: R1 = { | a i-1,a i ∈ D, i=2,...,n } InitList( &L ) InitList( &L ) DestroyList( &L ) DestroyList( &L ) ListEmpty( L ) ListEmpty( L ) ListLength( L ) ListLength( L ) GetElem( L, i, &e ) GetElem( L, i, &e ) … … … … } ADT List } ADT List

9 课程代码: School of Computer Science &Technology 9 A list can be implemented using arrays on a machine. 1 ) data elements are stored in a contiguous manner. If an element is represented by d bytes, then If an element is represented by d bytes, then the n-length list is : the n-length list is : the position of the i’th element: Loc(a i )=Loc(a i-1 )+d Loc(a i )=Loc(a 1 )+(i-1)*d 1 ≤ i ≤ n ——Random Access ——Random Access Simple Array Implementation of Lists

10 课程代码: School of Computer Science &Technology 10 # define List_Init_Size 100 // the initial size of list # define ListIncrement 10 // Incremental size typedef xxx Elemtype // the data type of each element typedef struct { Elemtype elem[List_Init_Size]; // using an array int length; //the length of list int listsize; //maximum size of list } SqList; 2) Array-based List

11 课程代码: School of Computer Science &Technology 11 SqList L ; L. elem[0] // the head element a 1 L. elem[L.length-1] // the last element a n L.length // the length of the list

12 课程代码: School of Computer Science &Technology 12 ① Initialization (construct an empty list) SqList init_SqList( ) { SqList L; L.elem = (ElemType *) malloc (List_Init_Size * sizeof (ElemType) ); if ( ! L.elem) exit(overflow); //Out of space L.length = 0; L.listsize = List_Init_Size; // initial size return L; } 3 ) Operations on Array-based List

13 课程代码: School of Computer Science &Technology 13 Where is the i’th element ElemType GetItem(Sqlist L, int i) { ElemType e; e = L.elem[i-1]; return e; } ② Retrieve the i’th element

14 课程代码: School of Computer Science &Technology 14 ③ Insert a new element at the position i SqList Insert_SqList(SqList L , int i , Elemtype x) { if ((i L.length+1)) return ERROE; //whether i is legal ? if (L.length >= L.listsize) // whether the list is full? { newbase = (ElemType *) realloc(L.elem, L.listsize+ListIncrement)*sizeof(ElemType)); if ( ! newbase) exit(overflow); // Out of space L.elem=newbase; L.listsize + =ListIncrement; } // allocate new storage space for (m =L.length-1; m >= i-1; --m) L.elem[m+1] = L.elem[m]; L.elem[i-1] = x; L.length ++; Return L; }

15 课程代码: School of Computer Science &Technology 15 n Algorithm Analysis: Asymptotic Time Complexity : F Best Case : when i = n+1 , T(n)=O(1) F Worst Case : when i=1, T(n)=O(n) F Average Case : T(n)=O(n)

16 课程代码: School of Computer Science &Technology 16 ④ Delete the element at position i

17 课程代码: School of Computer Science &Technology 17 SqList Delete_SqList(SqList L, int i , Elemtype e) { if ((i L.length)) // whether i is legal ? return ERROE; e = L.elem[i-1]; //retrieve the i’th element for ( i; i<=L.length-1; ++i ) L.elem[i-1] = L.elem[ i ] ; // elements move backward --L.length; // length-1 Return L; }

18 课程代码: School of Computer Science &Technology 18 Algorithm Analysis: F Best Case : when i = n , T(n)=O(1) F Worst Case : when i=1, T(n)=O(n) F Average Case : T(n)=O(n)

19 课程代码: School of Computer Science &Technology 19 ⑤ Find the first occurrence of X x = 48 x = 50

20 课程代码: School of Computer Science &Technology 20 int LocateElem_Sq(SqList L , Elemtype x) { int i = 1; while( I <= L.length && L.elem[i -1] != x) i ++; if (i >L.length) return -1; else return i; /*Return the position of x */ }

21 课程代码: School of Computer Science &Technology 21 Summary of array-based list Array implementation of list  successive element are adjacent in memory disadvantage  Element movements during insertion and deletion  Waste considerable space in storing the list of varying size possible solution  linked list  linked lists are dynamically allocated

22 课程代码: School of Computer Science &Technology Linked List Linked list  Successive elements are not necessarily adjacent in memory. Instead, data is stored at random locations and the current data location provides the information regarding the location of the next data.  Elements connected by pointer links. Using pointers to point to the next element. Use a linked list instead of an array when  You have an unpredictable number of data elements  Insertion and deletion are frequent

23 课程代码: School of Computer Science &Technology 23  Singly linked list Begins with a pointer to the first node Terminates with a null pointer Only traversed in one direction  Circular, singly linked list Pointer in the last node points back to the first node  Doubly linked list Each node has a forward pointer and a backward pointer Allows traversals both forwards and backwards  Circular, doubly linked list Forward pointer of the last node points to the first node and backward pointer of the first node points to the last node  Types of linked list:

24 课程代码: School of Computer Science &Technology 24 1) Singly Linked List Each structure contains the element and a pointer to a structure containing its successor, called a node. Link pointer in the last node is set to null to mark the list ’ s end. Accessed via a pointer to the first node of the list. e.g. (a1,a2,a3,a4)

25 课程代码: School of Computer Science &Technology 25

26 课程代码: School of Computer Science &Technology 26 2) Linked List with a header In practice, we keep a sentinel node, referred as a header or dummy node. In practice, we keep a sentinel node, referred as a header or dummy node. The header is in position 0. The header is in position 0. An un-empty linked list Empty list with header

27 课程代码: School of Computer Science &Technology 27 3) Linked List Implementation Typedef struct Lnode{ Typedef struct Lnode{ ElemType data ; // Data Field ElemType data ; // Data Field Struct Lnode *next; // Pointer (Link) Field Struct Lnode *next; // Pointer (Link) Field}Lnode,*LinkList; LinkList L; // Lnode *L; The location of the first element: L->next Value for the first element : L->next->data

28 课程代码: School of Computer Science &Technology 28 4 ) Operations on linked list ① Insertion into a Listed List e.g. Insert a new node before the i’th node e.g. Insert a new node before the i’th node Before insert (After insert)

29 课程代码: School of Computer Science &Technology 29 Linklist ListInsert (LinkList L, int i, Elemtype x ) { // 在带头结点单链表第 i 个结点前插入新元素 x p=L; j=0; while ( p != NULL && j< i - 1 ) { p = p→next; j++; } // 找第 i-1 个结点 if ( p == NULL || j>i-1 ) return Error; newnode= (LinkList ) malloc(sizeof(Lnode)); // 创建新结点, 其数据为 x newnode→data=x; newnode→next = p→next; p→next = newnode; return (L); }  T(n) = O(n)

30 课程代码: School of Computer Science &Technology 30 ② Create a linked List  Analyzing 1) Create an empty linked list 2) Insert n nodes after the header

31 课程代码: School of Computer Science &Technology 31 Linklist CreateList_L ( int n ) { LinkList L; { LinkList L; L= (LinkList) malloc(sizeof(Lnode)); L= (LinkList) malloc(sizeof(Lnode)); L->next=NULL; // 建立一个空表 L->next=NULL; // 建立一个空表 for( i=n; i>0 ; --i ) for( i=n; i>0 ; --i ) { p= (LinkList) malloc(sizeof(Lnode)); { p= (LinkList) malloc(sizeof(Lnode)); // 为新结点分配存储单元 // 为新结点分配存储单元 scanf(&P->data); // 读入要插入元素值 scanf(&P->data); // 读入要插入元素值 p->next= L->next; L->next=p; // 修改链接关系 p->next= L->next; L->next=p; // 修改链接关系 } return(L); return(L); } T(n) =O(n) T(n) =O(n)

32 课程代码: School of Computer Science &Technology 32 ③ Deletion of an Element from a List Delete the i’th element from the list

33 课程代码: School of Computer Science &Technology 33 Linklist ListDelete (LinkList L, int i, ElemType &e ) { // 在单链表中删除第 i 个结点 p =L; j = 0; while ( p →next && j< i - 1 ) { p = p→next; j++; } // 找第 i-1 个结点 if ( !(p →next)|| j>i-1) return Error; q=p→next; p→next=q→next; // 重新链接 e= q→data; free(q); // 释放 q 结点 return(L); }  T(n) = O(n)

34 课程代码: School of Computer Science &Technology 34 ④ ④ Find the first occurrence of X LinkList Locate_LinkList( LinkList L, ElemType x) /* 在单链表 L 中查找值为 x 的结点,找到后返回其指针, 否则返回空 */ /* 在单链表 L 中查找值为 x 的结点,找到后返回其指针, 否则返回空 */ { LinkList p; { LinkList p; p=L->next; p=L->next; while ( p!=NULL && p->data != x) while ( p!=NULL && p->data != x) p=p->next; // 向后查找 p=p->next; // 向后查找 return p; return p; } T(n) =O(n) T(n) =O(n)

35 课程代码: School of Computer Science &Technology 35 ⑤ Count the Elements of a linked List int Listlength_L ( LinkList L) int Listlength_L ( LinkList L) { i=0; p=L; { i=0; p=L; while ( p->next !=NULL) while ( p->next !=NULL) { i++ ; p= p->next; } { i++ ; p= p->next; } return(i); return(i); } T(n) =O(n) T(n) =O(n)

36 课程代码: School of Computer Science &Technology 36 Subsequent nodes are accessed via the link-pointer member of the current node.  When insertion or deletion, locating the predecessor node. A Linked list is accessed via a pointer to the first node of the list.  Linked list is sequential access structure. Summary of singly linked list

37 课程代码: School of Computer Science &Technology Circular, singly linked list 1 ) A singly linked list that the pointer in the last node points back to the first node.

38 课程代码: School of Computer Science &Technology 38 In a circularly singly linked list, every elements can be accessed from an node. In a circularly singly linked list, every elements can be accessed from an node. A circular, singly linked list with trail pointer A circular, singly linked list with trail pointer The last element : *rear The first element : rear->next->next

39 课程代码: School of Computer Science &Technology 39 2) Circularly singly linked list implementation Typedef struct Lnode { Typedef struct Lnode { ElemType data ; // Data Field ElemType data ; // Data Field Struct Lnode *next; // Pointer (Link) Field Struct Lnode *next; // Pointer (Link) Field } Lnode,*LinkList; (Same as singly linked list) } Lnode,*LinkList; (Same as singly linked list) 3 ) Operation on circularly singly linked list:  Create  Length  Locate :  Insertion :  Deletion : Where is the end of the circular linked list Same as singly linked list

40 课程代码: School of Computer Science &Technology 40 E.g. Count the Elements of a circular linked List : E.g. Count the Elements of a circular linked List : int Listlength_CL (LinkList L) int Listlength_CL (LinkList L) { j=0; p=L->next; { j=0; p=L->next; while (p!= L ) while (p!= L ) { j++; p=p->next;} { j++; p=p->next;} return ( j ); return ( j ); }

41 课程代码: School of Computer Science &Technology Doubly linked list 1) Each node contains a data field and two pointer fields, a forward pointer and a backward pointer. Allows traversals both forwards and backwards.  Circular, doubly linked list

42 课程代码: School of Computer Science &Technology 42 2) Doubly linked list implementation Typedef struct DuLnode{ Typedef struct DuLnode{ ElemType data; // Data Field ElemType data; // Data Field Struct DuLnode * prior, *next; // Pointer Field Struct DuLnode * prior, *next; // Pointer Field}DuLnode,*DuLinkList; p->next->prior = p->prior->next

43 课程代码: School of Computer Science &Technology 43 3) Operations for doubly Linked List ① Insertion into a doubly Listed List DuLinkList ListInsert_Dul(DuLinklist L,int i, Elemtype x) { if ( !(p=GetElemP_Dul(L,i))) return ERROR; if (! (s = (DuLinklist)malloc(sizeof(DuLnode)))) return ERROR; s->data = x; s->prior = p->prior; p->prior->next = s; s->next = p; p->prior = s; return (L); }

44 课程代码: School of Computer Science &Technology 44 ② Delete an Element from a doubly List DuLinkList ListDelete_Dul(DuLinklist L,int i, Elemtype &e) { if ( !( p =GetElemP_Dul(L,i))) return ERROR; e=p->data; p->prior->next = p->next; p->next->prior = p->prior; free (p); return (L); }

45 课程代码: School of Computer Science &Technology 45 P n (x) (n+1 items)  Coefficient: a 0, a 1, a 2, …, a n  Exponent: 0, 1, 2, …, n 1) Polynomials Example: Polynomials

46 课程代码: School of Computer Science &Technology 46 2 ) Representation Array-based implementation Disadvantage: for sparse polynomials e.g. P 101 (x) = 3 + 5x x 101 e.g. P 101 (x) = 3 + 5x x 101

47 课程代码: School of Computer Science &Technology 47   An item represent by a node typedef struct poly_node { int coef; int expn; struct poly_node *next; }; Linked list implementation  e.g. AH = x 6 + 2x 8 +7x 14

48 课程代码: School of Computer Science &Technology 48 3 ) Adding Polynomials AH = x 6 + 2x 8 +7x 14 BH = - x x 6 - 3x x 14 +4x 18

49 课程代码: School of Computer Science &Technology 49 Summary of Linked list Advantanges of linked list: store items "sequentially" without restrictions on location insert new item without shifting delete existing item without shifting size can expand/contract throughout use Disadvantages overhead of links: used only internally, pure overhead no longer have direct access to each element of the list. O(1) access becomes O(n) access since we must go through first element, and then second, and then third, etc.

50 课程代码: School of Computer Science &Technology 50 Comparison of Implementation Array-Based List:  Insertion and deletion are O(n).  Direct access are O(1).  Array must be allocated in advance.  No overhead if all array positions are full. Linked List:  Insertion and deletion are O(1).  Direct access are O(n).  Space grows with number of elements.  Every element requires overhead.

51 课程代码: School of Computer Science &Technology 51 Contiguous storage is generally preferable:  when the entries are individually very small;  when the size of the list is known when the program is written;  when few insertions or deletions need to be made except at the end of the list; and  when random access is important. Linked storage proves superior  when the entries are large;  when the size of the list is not known in advance; and  when flexibility is needed in inserting, deleting, and rearranging the entries.

52 课程代码: School of Computer Science &Technology Stack stack at one endtop 1) Definition: A stack is a data structure in which all insertions and deletions of elements are made at one end, called the top of the stack. The last element which is inserted is the first one that will be removed. Characteristic:  Characteristic: Last In First Out

53 课程代码: School of Computer Science &Technology 53 Stack model  A stack is a list with the restriction that insertion & deletion can be performed only at the end (or top) of the list. (Restricted form of list)  Only the top node is accessible: New nodes can be added and removed only at the top  Last-in, first-out (LIFO) Notation:  Insert: PUSH — Adds a new node to the top of the stack  Delete: POP — Removes a node from the top  The accessible element is called TOP.

54 课程代码: School of Computer Science &Technology 54 ADT Stack { Objects: D = { a i | a i ∈ ElemSet, i=1,2,...,n, n≥0 } Objects: D = { a i | a i ∈ ElemSet, i=1,2,...,n, n≥0 } Function : R1 = { |a i-1,a i ∈ D, i=2,...,n } Function : R1 = { |a i-1,a i ∈ D, i=2,...,n } InitStack (&S) : Create the stack, leaving it empty. DestroyStack(&S) : Destroy a stack. DestroyStack(&S) : Destroy a stack. Push(&S,e):Push a new entry onto the top of the stack Push(&S,e):Push a new entry onto the top of the stack Pop (&S ) : Pop the entry off the top of the stack Pop (&S ) : Pop the entry off the top of the stack GetTop (S ): Retrieve the Top entry from the stack GetTop (S ): Retrieve the Top entry from the stack IsEmpty (S): Test whether the stack is Empty. IsEmpty (S): Test whether the stack is Empty. … … … … } ADT Stack ADT of Stacks 2 ) ADT of Stacks

55 课程代码: School of Computer Science &Technology 55 1) Array implementation of stack # define Stack_Init_Size 100; // the initial size # define StackIncrement 10; // Incremental size typedef XXX Elemtype; typedef struct { Elemtype *base; // Elemtype base[Stack_Init_Size] int top; //the top of stack int MaxSize; //maximum size of stack }SqStack ; Implementation of Stacks

56 课程代码: School of Computer Science &Technology 56 SqStack S;

57 课程代码: School of Computer Science &Technology 57 ① Initialization (create an empty stack) u Allocate storage space (Stack_Init_Size) u S.top = -1 ( an empty stack)  Algorithm SqStack Init_SqStack ( ) { S.base = (Elemtype *) malloc (Stack_Init_Size * sizeof(Elemtype)); S.top= -1; S.MaxSize = Stack_Init_Size; return S; } Operation on Array-Based Stack

58 课程代码: School of Computer Science &Technology 58 u Whether the stack is Empty ( S.top= -1)  Get the top element  Algorithm Elemtype GetTop_SqStack (SqStack S) { if (S.top = = -1 ) return ERROR; /* empty stack*/ e = *(S.top); // e = S.base [S.top ]; return e; } ② Get the top element of the stack top S4 S3 S2 S1

59 课程代码: School of Computer Science &Technology 59 ③ Push  Algorithm SqStack Push (SqStack S, Elemtype x) { if (S.top >= S.MaxSize -1) //whether stack is full? { S.base = (Elemtype *) realloc (S.base, (S.MaxSize +StackIncrement) *sizeof(Elemtype)); if (!S.base) exit (OVERFLOW); //Out of space S.top = S. MaxSize -1; S.MaxSize + = StackIncrement; } S.top ++; *S.top = x; // S.base [S.top ]= x return S; }

60 课程代码: School of Computer Science &Technology 60 u Whether the stack is Empty? (S.top = -1) u e = *(S.top), S.top –1  Algorithm SqStack Pop (SqStack S, Elemtype &e) { if (S.top ==-1) return ERROR; //whether stack is empty e=*(S.top); // e = S.base [S.top ] S.top --; return S; } ④ Pop

61 课程代码: School of Computer Science &Technology 61 2)Linked List implementation of stack An linked stack with a header node

62 课程代码: School of Computer Science &Technology 62 typedef struct Node { Elemtype data; struct node *next; } Node, *LinkStack; // Node *top; LinkStack top; // Node *top;

63 课程代码: School of Computer Science &Technology 63 ① Push: insert element at the front of the list Operation on Linked Stack top newnode top newnode

64 课程代码: School of Computer Science &Technology 64  Algorithm (with a header): P59  Algorithm (no header) Link Stack Push (LinkStack top, Elemtype x) { LinkStack p; // A Linked stack can never be full p = (LinkStack) malloc(sizeof (LinkStack)); if ( ! p) exit(overflow); //Out of space p->data = x; p->next = top; top = p; return top; }

65 课程代码: School of Computer Science &Technology 65  Algorithm (with a header): P60  Algorithm (no header) LinkStack PopStack (LinkStack top, Elemtype e { if ( top == NULL) return NULL; //A stack can be empty, “pop” from an empty stack is an error else { e = top->data; p = top; top=top->next; free (p); } return top; } ② Pop: delete element at the front of the list

66 课程代码: School of Computer Science &Technology 66 1) Bracket Matching Using a stack to check whether brackets are balanced in a file.  Read characters until end of file  If the character is an left bracket, push it onto the stack.  If it is a right bracket, then  If the stack is empty, report an error.  Otherwise, pop the stack.  At the end of file, if the stack is not empty, report an error Applications

67 课程代码: School of Computer Science &Technology 67  Infix expression: A*(B+C)  Postfix expression: ABC+* How to convert the infix expression into postfix?  When an operand(numbers, usually) is entered, it is placed onto the output  When an operator (like addition, subtraction, multiplication, or division) is read  If it has higher priority than the top entry of the operator stack, it is pushed onto a stack;  Otherwise, pop the entries from the stack until we find an entry of lower priority.  If we read the end of input, pop the stack until it is empty. 2 ) Reverse Polish Calculator

68 课程代码: School of Computer Science &Technology 68 3 ) Stacks and Recursion  Definition: Recursion simply means a function that calls itself directly or indirectly.  Recursion should be used freely in the initial design of algorithms.It is especially appropriate where the main step toward solution consists of reducing a problem to one or more smaller cases.

69 课程代码: School of Computer Science &Technology 69  Informal definition: The factorial function of a positive integer is n! = n  (n-1)  …  1  Formal definition:  Algorithm: long Factorial ( long n ) { if ( n == 0 ) return 1; else return n*Factorial (n - 1); } Definition is recursive

70 课程代码: School of Computer Science &Technology 70 Structure is recursive Find the last element of a list void Find ( LinkList L ) { if ( L → next == NULL ) printf ( L → data); else Find ( L → next ); } Example: Linked List Example: Linked List

71 课程代码: School of Computer Science &Technology 71 Example: Tower of Hanoi Solution method is recursive

72 课程代码: School of Computer Science &Technology 72  Every recursive process consists of two parts:  A smallest, base case that is processed without recursion; (termination condition)  A general method that reduces a particular case to one or more of the smaller cases, thereby making progress toward eventually reducing the problem all the way to the base case.

73 课程代码: School of Computer Science &Technology 73 The general form of a recursive algorithm void p (parameters) void p (parameters) if ( stopping condition) if ( stopping condition) base case that is processed without recursion base case that is processed without recursion else p (smaller parameters); else p (smaller parameters); //recursive case

74 课程代码: School of Computer Science &Technology 74 Designing Recursive Algorithms  Find the key step. Begin by asking yourself,“How can this problem be divided into parts?”or “How will the key step in the middle be done?”  Find a stopping rule. This stopping rule is usually the small, special case that is trivial or easy to handle without recursion.  Outline your algorithm. Combine the stopping rule and the key step, using an if statement to select between them.  Check termination. Verify that the recursion will always terminate. Be sure that your algorithm correctly handles extreme cases.

75 课程代码: School of Computer Science &Technology 75 main ( ) int fact (int n) { int m , n= 3 ; { int f; m=fact(n) ; if (n==0) f=1; R1 : printf (“%d!=%d\n”,n,m); else f = n*fact(n-1); } R2: return f; } The Stack: Stacks and Recursion

76 课程代码: School of Computer Science &Technology Queues Queue front rear 1) Definition: A Queue is a data structure in which insertions take place at one end and deletions take place at the opposite end. Nodes are removed only from the head, called the front. Nodes are inserted only at the tail,called the rear. Characteristic:  Characteristic: F irst I n F irst O ut

77 课程代码: School of Computer Science &Technology 77 Queue model  A queue is a list, with insertion done only at one end and deletion done at the other end. (Restricted form of list)  First-in, first-out (FIFO)  Similar to a supermarket checkout line , I/O buffers … Notation:  Insert: Enqueue — insert an element at the end of the queue  Delete: Dequeue — delete (and return) the element at the start of the queue  First element: Front  Last element: Rear

78 课程代码: School of Computer Science &Technology 78 ADT Queue { Objects: D = { a i | a i ∈ ElemSet, i=1,2,...,n, n≥0 } Objects: D = { a i | a i ∈ ElemSet, i=1,2,...,n, n≥0 } Function : R1 = { |a i-1,a i ∈ D, i=2,...,n } Function : R1 = { |a i-1,a i ∈ D, i=2,...,n } InitQueue ( &Q) : Create a queue, leaving it empty. DestoryQueue (&Q) : Destroy a queue. DestoryQueue (&Q) : Destroy a queue. EnQueue (&Q, e) : insert e at the end of the queue EnQueue (&Q, e) : insert e at the end of the queue DeQueue (Q, &e): delete (and return) the element at DeQueue (Q, &e): delete (and return) the element at the start of the queue the start of the queue QueueEmpty (S): Test whether the queue is Empty. QueueEmpty (S): Test whether the queue is Empty. … … … … } ADT Queue ADT of Queues 2 ) ADT of Queues

79 课程代码: School of Computer Science &Technology 79 1) Linked list implementation  The storage structure would be a linked list.  Operating as a list  Keeping pointer to both the head and tail of the list Implementation of Queues  Empty Queue : Q.front=Q.rear

80 课程代码: School of Computer Science &Technology 80 The node The node typedef struct Qnode typedef struct Qnode { Elemtype data; { Elemtype data; struct QNode *next; struct QNode *next; } Qnode,*Queueptr; } Qnode,*Queueptr; Linked Queue Linked Queue typedef struct typedef struct { Queueptr front; { Queueptr front; Queueptr rear; Queueptr rear; } LinkQueue; } LinkQueue; LinkQueue Q; The front node : Q.front->next Q.front->next The rear node : Q.rear Q.rear

81 课程代码: School of Computer Science &Technology 81 ① EnQueue Operation on Linked Queue Algorithm: Algorithm: Queueptr EnQueue (LinkQueue Q, Elemtype x) Queueptr EnQueue (LinkQueue Q, Elemtype x) { P = (Queueptr) malloc (sizeof (QNode)); // 申请结点空间 { P = (Queueptr) malloc (sizeof (QNode)); // 申请结点空间 if ( !P ) exit (overflow); if ( !P ) exit (overflow); P->data = x; P->next = NULL; P->data = x; P->next = NULL; Q.rear->next = P; Q.rear = P; Q.rear->next = P; Q.rear = P; return Q; return Q;}

82 课程代码: School of Computer Science &Technology 82 ② DeQueue Queueptr DeQueue (LinkQueue Q, Qelemtype &e) { if (Q.front==Q.rear) return ERROR; { if (Q.front==Q.rear) return ERROR; /* 空队列 */ /* 空队列 */ P = Q.fornt->next; e = P->data; P = Q.fornt->next; e = P->data; /* p 指向队头结点 */ /* p 指向队头结点 */ Q.front->next = P->next; /* 删除队头结点 */ Q.front->next = P->next; /* 删除队头结点 */ if (Q.rear == P) Q.rear = Q.front; if (Q.rear == P) Q.rear = Q.front; /* p 是队中最后一个结点 */ /* p 是队中最后一个结点 */ free(P); return Q; free(P); return Q; }

83 课程代码: School of Computer Science &Technology 83 Sequence Queue Sequence Queue u an array to store the elements of the queue 。 u markers for the front and for the rear of the queue. 2) Array Implementation

84 课程代码: School of Computer Science &Technology 84 define MaxSize 100 /*the maximin size of queue */ typedef struct { Elemtype data[MaxSize]; // storage the element Elemtype data[MaxSize]; // storage the element int front; // point to the front int front; // point to the front int rear; // point to the next position of the rear int rear; // point to the next position of the rear}SqQueue;

85 课程代码: School of Computer Science &Technology 85

86 课程代码: School of Computer Science &Technology 86 A potential problem: “run out of space ” A potential problem: “run out of space ”  Solution: whenever front or rear gets to the end of the array, it is wrapped around to the beginning——Circular array implementation C D E F front rear E C D F front rear

87 课程代码: School of Computer Science &Technology 87  Circular Queue Dequeue : Dequeue : front = (front + 1) % MaxSize; front = (front + 1) % MaxSize; Enqueue : Enqueue : rear = (rear + 1) % MaxSize; rear = (rear + 1) % MaxSize;

88 课程代码: School of Computer Science &Technology 88 It is Empty : It is Empty : It is Full : It is Full : front == (rear + 1) % MaxSize; front rear front rear C D E F G B front == rear ; Problem: How to distinguish between empty & full?? Common Solutions: Keep an empty slot between front and rear

89 课程代码: School of Computer Science &Technology 89 ① EnQueue Operation on Circular Queue SqQueue EnSqQueue (SqQueue Q, Elemtype x) { if (Q.front == (Q.rear + 1) % MaxSize) return Error; /* 队满不能入队 */ return Error; /* 队满不能入队 */ else else { Q.data[Q.rear] = x; // 插入元素存入队尾 { Q.data[Q.rear] = x; // 插入元素存入队尾 Q.rear = (Q.rear + 1) % MaxSize; Q.rear = (Q.rear + 1) % MaxSize; /* 修改尾指针,入队完成 */ /* 修改尾指针,入队完成 */ } return Q; return Q;}

90 课程代码: School of Computer Science &Technology 90 ② DeQueue SqQueue DeSqQueue(SqQueue Q, Elemtype &e) { if (Q.front == Q.rear) return Error; /* 队空 */ else else { e = Q.data[Q.front]; // 取出队头元素 { e = Q.data[Q.front]; // 取出队头元素 Q.front = (Q.front + 1) % MaxSize; Q.front = (Q.front + 1) % MaxSize; /* 修改头指针,出队完成 */ /* 修改头指针,出队完成 */ } return Q; return Q;}

91 课程代码: School of Computer Science &Technology 91 1) Simulation of an Airport  The same runway is used for both landings and takeoffs.  One plane can land or take off in a unit of time, but not both.  A random number of planes arrive in each time unit.  A plane waiting to land goes before one waiting to take off.  The planes that are waiting are kept in queues landing and takeoff, both of which have a strictly limited size Applications of Queues

92 课程代码: School of Computer Science &Technology 92 Summary: Summary: Queues vs. Stacks  Stacks are a LIFO container => store data in the reverse of order received  Queues are a FIFO container => store data in the order received  Stacks then suggest applications where some sort of reversal or unwinding is desired.  Queues suggest applications where service is to be rendered relative to order received.  Stacks and Queues can be used in conjunction to compare different orderings of the same data set.  From an ordering perspective, then, Queue are the “ opposite ” of stacks => Easy solution to the palindrome problem

93 课程代码: School of Computer Science &Technology 93


Download ppt "DATA STRUCTURE Instructor: Dai Min Instructor: Dai Min Office: XNA602 Office: XNA602 Fall 2006."

Similar presentations


Ads by Google