STACK Data Structure:
|
|
- Lenard Daniel
- 7 years ago
- Views:
Transcription
1 STACK Data Structure: Data Structures using C Chapter-3 STACK AND QUEUE A stack is an ordered list in which insertions and deletions are made at one end called the top. o If we add the elements A, B, C, D, E to the stack, in that order, then E is the first element we delete from the stack o A stack is also known as a Last-In-First-Out (LIFO) list. Fig: Insert and Delete Elements in the stack Primitive Operations on Stack push An item is added to a stack i.e. it is pushed onto the stack. pop An item is deleted from the stack i.e. it is popped from the stack. Working of stack: Stack, which contains max_size number of elements. The element item is inserted in the stack at the position top. Initially top is set to 1. Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 1
2 Since the push operation adds elements into a stack, the stack is also called as pushdown list. If there are no elements in a stack it is considered as empty stack. If the size of the stack is full then it is called stack overflow. The push operation is not applicable on full stack otherwise an overflow condition occurs. The pop operation is not applicable on an empty stack otherwise an underflow condition arises. We need to have a new operation empty(s) that checks whether a stack s is empty or not. Another operation on a stack is to determine what the top item of the stack is without removing it. stacktop(s) returns the top element of the stack s. Stack ADT: ADT Stack is objects: a finite ordered list with zero or more elements. functions: for all stack Stack, item element, max_stack_size positive integer Stack CreateS(max_stack_size) ::=create an empty stack whose maximum size is max_stack_size Boolean IsFull(stack, max_stack_size) ::=if(number of elements in stack == max_stack_size) return TRUE else return FALSE Stack Push(stack, item) ::=if(isfull(stack)) stack_fullelseinsert iteminto top of stackand returnabstract BooleanIsEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSE ElementPop(stack) ::= if(isempty(stack)) return Else remove and return the item on the top of the stack. Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 2
3 Implementation of stack: using array StackCreateS(max_stack_size)::= #define MAX_STACK_SIZE 100 /* maximum stack size */ typedefstruct int key; /* other fields */ element; element stack[max_stack_size]; //declaration of structure variable int top = -1; Boolean IsEmpty(Stack)::= top< 0; Boolean IsFull(Stack) ::= top >= MAX_STACK_SIZE-1; Add and Item to Stack: push() void push(element item) /* add an item to the global stack */ if (top >= MAX_STACK_SIZE-1) stackfull( ); return; stack[++top] = item; Delete an Item to Stack: pop() element pop() /* return the top element from the stack */ if (top == -1) return stackempty( ); /* returns and error key */ return stack[top--]; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 3
4 Stack full: void stackfull() fprintf(stderr, Stack is full, cannot add element ); exit(exit_failre); StackCreateS()::= Stack Using Dynamic Arrays: #define MAX_STACK_SIZE 100 /* maximum stack size */ typedefstruct int key; /* other fields */ element; element *stack; //declaration of structure variable MALLOC (stack, sizeof(*stack)); int capacity=1; int top= -1; Boolean IsEmpty(Stack)::= top< 0; Boolean IsFull(Stack) ::= top >= capacity-1; Add and Item to Stack: push() void push(int *top, element item) /* add an item to the global stack */ if (*top >= MAX_STACK_SIZE-1) stackfull( ); return; stack[++*top] = item; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 4
5 Delete an Item to Stack: pop() element pop(int *top) /* return the top element from the stack */ if (*top == -1) return stackempty( ); /* returns and error key */ return stack[(*top)--]; Stack full: void stackfull() fprintf(stderr, Stack is full, cannot add element ); exit(exit_failre); Queue Data Structure: A queue is an ordered list in which all insertion take place one end, called the rear and all deletions take place at the opposite end, called the front If we insert the elements A, B, C, D, E, in that order, then A is the first element we delete from the queue A Queue is also known as a First-In-First-Out (FIFO) list Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 5
6 Queue ADT: Structure Queue is objects: a finite ordered list with zero or more elements. functions: for all queue Queue, item element, max_ queue_ size positive integer Queue CreateQ(max_queue_size) ::= create an empty queue whose maximum size is max_queue_size Boolean IsFullQ(queue, max_queue_size) ::= if(number of elements in queue == max_queue_size) return TRUE else return FALSE QueueAddQ(queue, item) ::= if(isfullq(queue)) queue_full Else insert item at rear of queue and return queue Boolean IsEmptyQ(queue) ::= if(queue==createq(max_queue_size)) return TRUE else returnfalse ElementDeleteQ(queue) ::=if (IsEmptyQ(queue)) return Else remove and return the item at front of queue. Implementation of Queue using Arrays: Queue CreateQ(max_queue_size) ::= #define MAX_QUEUE_SIZE 100/* Maximum queue size */ typedef struct int key; /* other fields */ element; element queue[max_queue_size]; int rear = -1; int front = -1; Boolean IsEmpty(queue) ::= front == rear Boolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1 Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 6
7 Add an Element to Queue: void addq(element item) /* add an item to the queue */ if (rear == MAX_QUEUE_SIZE-1) queuefull( ); queue [++rear] = item; queuefull() printf( Queue is Full ); return or exit(); Add an Element to Queue using Pointer: void addq(int *rear, element item) /* add an item to the queue */ if (*rear == MAX_QUEUE_SIZE-1) queuefull( ); return; queue [++*rear] = item; queuefull() printf( Queue is Full ); return or exit(); Delete from a Queue: element deleteq() /* remove element at the front of the queue */ if ( front == rear) return queueempty( ); /* return an error key */ return queue [++front]; Delete from a Queue using Pointer: element deleteq(int*front, intrear) /* remove element at the front of the queue */ if ( *front == rear) return queueempty( ); /* return an error key */ return queue [++ *front]; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 7
8 Queue Empty: IsEmptyQ(queue) return (front == rear) Queue Full IsFullQ(queue) return rear == (MAX_QUEUE_SIZE-1) Applications of Queue: Queues, like stacks, also arise quite naturally in the computer solution of many problems. Perhaps the most common occurrence of a queue in computer applications is for the scheduling of jobs. In batch processing the jobs are ''queued-up'' as they are readin and executed, one after another in the order they were received. This ignores the possible existence of priorities, in which case there will be one queue for each priority. When we talk of queues we talk about two distinct ends: the front and the rear. Additions to the queue take place at the rear. Deletions are made from the front. So, if a job is submitted for execution, it joins at the rear of the job queue. The job at the front of the queue is the next one to be executed Solving Job Scheduling Algorithm using Queue data Structure in Operating System: creation of job queue - in the operating system which does not use priorities, jobs are processed in the order they enter the system. front rear Q[0] Q[1] Q[2] Q[3] Comments J1 queue is empty job 1 is added -1 1 J1 J2 job 2 is added -1 2 J1 J2 J3 job 3 is added 0 2 * J2 J3 job 1 is deleted 1 2 * * J3 job 2 is deleted Note: * representing empty Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 8
9 Problems with normal Queue: Queue gradually shifts to the right (as shown above in the job scheduling queue) queue_full(rear==max_queue_size-1) Queue_full does not always mean that there are MAX_QUEUE_SIZE items in queue there may be empty spaces available - Solution to save space: Circular queue Note: As the element in the queue are getting filled the rear getting incremented, but as the element getting deleted from the queue the front is also incrementing where we are wasting lots of memory without use of it as shown in the above fig of job scheduling. Circular Queues more efficient queue representation - Representing the array queue[max_queue_size] as circular - Initially front and rear to 0 rather than -1 - The front index always points one position counterclockwise from the first element in the queue - The rear index points to the current end of the queue empty queue Non empty Queue Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 9
10 Add to Circular Queue: void addq(element item) /* add an item to the queue */ rear = (rear +1) % MAX_QUEUE_SIZE; if (front == rear) /* reset rear and print error */ queuefull( ); queue[rear] = item; queuefull() printf( Queue is Full ); return or exit(); Delete from Circular Queue: element deleteq() element item; /* remove front element from the queue and put it in item */ if (front == rear) return queueempty( ); /* returns an error key */ front = (front+1) % MAX_QUEUE_SIZE; return queue[front]; queuefull() printf( Queue is Empty ); return or exit(); Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 10
11 Add to Circular Queue using Pointers: void addq(intfront, int*rear, element item) /* add an item to the queue */ *rear = (*rear +1) % MAX_QUEUE_SIZE; if (front == *rear) /* reset rear and print error */ queuefull( ); queue[*rear] = item; Delete from Circular Queue using Pointers: element deleteq(int* front, intrear) element item; /* remove front element from the queue and put it in item */ if (*front == rear) return queueempty( ); /* returns an error key */ *front = (*front+1) % MAX_QUEUE_SIZE; return queue[*front]; queuefull() printf( Queue is Empty ); return or exit(); Circular Queue using dynamically Allocated Arrays Suppose that a dynamically allocated array is used to hold the elements. Let capacity be the number of positions in the array queue. To add an element to a full queue, we must first increase the size of this array using the function realloc. As with dynamically allocated stacks, we use array doubling. However it isn t sufficient to simply double the array size using realloc. Consider the full queue as shown in fig (a). This figure shows the queue with seven elements I an array whose capacity is 8. To visualize array doubling when a circular queue used, it is better to flatten out the array as in fig (b). Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 11
12 Fig (c) shows the array after doubling by realloc. To get a proper circular queue configuration, we must slide the elements in the right segment (i.e. element A and B)to the right end of the array as in fig (d). To get the configuration as in fig (e) we must follow the following method: 1) Create a new array newqueue of twice the capacity. 2) Copy the second segment (i.e. the elements queue[front + 1] till queue[capacity-1])to positions in newqueue beginning at 0. 3) Copy the first segment (i.e. the elements queue[0] till queue[rear] to position in newqueue beginning at capacity-front-1) Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 12
13 Code showing Doubling queue capacity: Void queuefull() /* allocate an array with twice the capacity */ element * newqueue; MALLOC(newQueue, 2*capacity*sizeof(*queue)); /* copy from queue to newqueue*/ int start = (front + 1) % capacity; if(start < 2) copy(queue+start, queue+start+capacity-1, newqueue ); else copy(queue+start, queue+capacity, newqueue ); copy(queue, queue+rear+1, newqueue+capacity-start ); /* Switch to newqueue */ front = 2*capacity-1; rear = capacity-2; capacity = capacity * 2; free(queue); queue = newqueue; void addq(element item) /* add an item to the queue */ rear = (rear + 1)% capacity; if (front == rear) queuefull(); queue[rear] = item; Add a Circular Queue: Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 13
14 A Mazing Problem: The rat-in-a-maze experiment is a classical one from experimental psychology. A rat (or mouse) is placed through the door of a large box without a top. Walls are set up so that movements in most directions are obstructed. The rat is carefully observed by several scientists as it makes its way through the maze until it eventually reaches the other exit. There is only one way out, but at the end is a nice hunk of cheese. The idea is to run the experiment repeatedly until the rat will zip through the maze without taking a single false path. The trials yield his learning curve. We can write a computer program for getting through a maze and it will probably not be any smarter than the rat on its first try through. It may take many false paths before finding the right one. But the computer can remember the correct path far better than the rat. On its second try it should be able to go right to the end with no false paths taken, so there is no sense re-running the program. Why don't you sit down and try to write this program yourself before you read on and look at our solution. Keep track of how many times you have to go back and correct something. This may give you an idea of your own learning curve as we re-run the experiment throughout the book. Experiment implementation: the representation of the maze - Two-dimensional array - Element 0: open path - Element 1: barriers Let us represent the maze by a two dimensional array, MAZE(1:m, 1:n), where a value of 1 implies a blocked path, while a 0 means one can walk right on through. We assume that the rat starts at MAZE (1,1) and the exit is at MAZE(m,n). Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 14
15 With the maze represented as a two dimensional array, the location of the rat in the maze can at any time be described by the row, i, and column, j of its position. Now let us consider the possible moves the rat can make at some point (i,j) in the maze. Figure 3.6 shows the possible moves from any point (i,j). The position (i,j) is marked by an X. If all the surrounding squares have a 0 then the rat can choose any of these eight squares as its next position. We call these eight directions by the names of the points on a compass north, northeast, east, southeast, south, southwest, west, and northwest, or N, NE, E, SE, S,SW, W, NW. Note: We must be careful here because not every position has eight neighbors. If (i,j) is on a border where either i = 1 or m, or j = 1 or n, then less than eight and possibly only three neighbors exist. To avoid checking for these border conditions we can surround the maze by a border of ones. [row][col] which is on border - has only three neighbors - surround the maze by a border of 1 s Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 15
16 m * p maze - requires (m + 2) * (p + 2) array - entrance position: [1][1] - exit position: [m][p] Another device which will simplify the problem is to predefine the possible directions to move in a table, MOVE(1:8.1:2), which has the values Representation in C typedef struct short int vert; short int horiz; offsets; offsets move[8];/* array of moves for each direction */ Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 16
17 If we are at position, maze[row][col], and we wish to find the position of the next move, maze[row][col], we set: next_row = row + move[dir].vert; next_col = col + move[dir].horiz; Initial attempt at a maze traversal algorithm -dimensional array, mark, to record the maze positions already checked pass history #define MAX_STACK_SIZE 100 /*maximum stack size*/ typedef struct short int row; short int col; short int dir; element; element stack[max_stack_size]; Maze Search Algorithm: void path(void) int i, row, col, nextrow, nextcol, dir, found=false; element position; /* structure variable */ mark[1][1]=1; top=0; stack[0].row=1; stack[0].col=1; stack[0].dir=1; while(top > -1 &&!found) position = pop(); row = position.row; col=position.col; dir = position.dir; while(dir < 8 &&!found) /* move in direction dir*/ nextrow = row + move[dir].vert; nextcol = col + move[col].horiz; if(nextrow == EXIT_ROW && nextcol == EXIT_COL) found = TRUE; else if(!maze[nextrow][nextcol] = col &&!mark[nextrow][nextcol]) mark[nextrow][nextcol] = 1; position.row = row; position.col = col; position.dir = ++dir; push(position); row = nextrow; col = nextcol; dir = 0; Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 17
18 else ++ dir; if(found) printf( The Path is: ); printf( row col ); for(i=0; i<=top; i++) printf( %d%d, stack[i].row, stack[i].col); printf( %d%d, row, col); printf( %d%d, EXIT_ROW, EXIT_COL); else printf( The maze Does not have Path ); Evaluating postfix expressions ssions is known as infix notation binary operator in-between its two operands expressions referred to as postfix -free notation Postfix: - no parentheses, - no precedence Infix 2+3*4 a*b+5 (1+2)*7 a*b/c ((a/(b-c+d))*(e-a)*c a/b-c+d*e-a*c Postfix 2 3 4*+ ab* * ab*c/ abc-d+/ea-*c* ab/c-de*+ac*- Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 18
19 Evaluating postfix expressions is much simpler than the evaluation of infix expressions: Before attempting an algorithm to translate expressions from infix to postfix notation, let us make some observations regarding the virtues of postfix notation that enable easy evaluation of expressions. To begin with, the need for parentheses is eliminated. Secondly, the priority of the operators is no longer relevant. The expression may be evaluated by making a left to right scan, stacking operands, and evaluating operators using as operands the correct number from the stack and finally placing the result onto the stack. This evaluation process is much simpler than attempting a direct evaluation from infix notation. of it. we make a single left-to-right scan an expression easily by using a stack Evaluating Postfix Expression: 6 2/3-4 2*+ 6 2 / * + Token Stack [0] [1] [2] /2 6/2 3 6/2-3 6/ / /2-3 4*2 6/2-3+4*2 top Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 19
20 Representation expression #define MAX_STACK_SIZE 100 /* max stack size */ #define MAX_EXPR_SIZE 100 /* max expression size */ typedef enum lparen, rparen, plus, minus,times, divide, mode, eos, operand precedence; int stack[max_stack_size]; /* global stack */ char expr[max_expr_size]; /* input string */ Function to evaluate a postfix expression eval() - if the token is an operand, convert it to number and push to the stack - otherwise 1) pop two operands from the stack 2) perform the specified operation 3) push the result back on the stack function to get a token get_token() - used to obtain tokens from the expression string Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 20
21 int eval() precedence token; char symbol; int op1, op2; int n = 0; int top = -1; token = get_token(&symbol, &n); while (token!= eos) if (token == operand) push(&top, symbol- 0 ); else op2 = pop(&top); op1 = pop(&top); switch (token) case plus: push(&top, op1+op2); break; case minus: push(&top, op1-op2); break; case times: push(&top, op1*op2); break; case divide: push(&top, op1/op2); break; case mod: push(&top, op1%op2); // end of else token = get_token(&symbol, &n); // end of while return pop(&top); precedence get_token(char *psymbol, int *pn) *psymbol = expr[(*pn)++]; switch (*psymbol) case ( : return lparen; case ) : return rparen; case + : return plus; case - : return minus; case * : return times; case / : return divide; case % : return mod; case : return eos; default : return operand; /* no error checking */ Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 21
22 Converging Infix to Postfix Different possible algorithms for producing a postfix expression from an infix one 1) Fully parenthesize the expression 2) move all binary operators so that they replace their corresponding right parentheses 3) Delete all parentheses For eg) a/b-c+d*e-a*c when fully parenthesized it becomes ((((a/b)-c)+(d*e))-a*c)) Perform step-2 and step-3 on the above parenthesized expression we will get ab/c-de*+ac*- This procedure is easy to work only by hand but difficult to be done using a computer. The problem with this as an algorithm is that it requires two passes: The first one reads the expression and parenthesizes it while the second actually moves the operators. As we have already observed, the order of the operands is the same in infix and postfix. So as we scan an expression for the first time, we can form the postfix by immediately passing any operands to the output. Then it is just a matter of handling the operators. The solution is to PUSH them in a stack until just the right moment and then to POP from stack and pass them to the output. 1) Simple expression: Simple expression a+b*c - yields abc*+ in postfix token a + b * c eos Stack [0] [1] [2] * + * top Output a a ab ab abc abc*+ Translation of a+b*c to postfix Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 22
23 Parenthesized expression Parentheses make the translation process more difficult - equivalent postfix expression is parenthesis-free expression a*(b+c)*d - yield abc+*d* in postfix right parenthesis - pop operators from a stack until left parenthesis is reached Token a * ( b + c ) * d eos Stack [0] [1] [2] * * ( * ( * ( + * ( + * * * * top output a a a ab ab abc abc+ abc+* abc+*d abc+*d* Translation of a*(b+c)*d to postfix Postfix: - no parenthesis is needed - no precedence is needed Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 23
24 Function to concert infix to postfix: void postfix(void) char symbol; precedence token; int n = 0; int top = 0; stack[0] = eos; for (token = get_token(&symbol, &n); token!= eos; token = get_token(&symbol, &n)) if (token == operand) printf( %c, symbol); else if (token == rparen) while (stack[top]!= lparen) print_token(pop(&top)); pop(&top); else while (isp[stack[top]] >= icp[token]) print_token(pop(&top)); push(&top, token); while ((token = pop(&top))!= eos) print_token(token); printf( \n ); Lecturer: Syed Khutubuddin Ahmed Contact: khutub27@gmail.com 24
Application of Stacks: Postfix Expressions Calculator (cont d.)
Application of Stacks: Postfix Expressions Calculator (cont d.) Postfix expression: 6 3 + 2 * = FIGURE 7-15 Evaluating the postfix expression: 6 3 + 2 * = Data Structures Using C++ 2E 1 Application of
More information1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++
Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The
More informationModule 2 Stacks and Queues: Abstract Data Types
Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which
More informationData Structures Using C++ 2E. Chapter 5 Linked Lists
Data Structures Using C++ 2E Chapter 5 Linked Lists Doubly Linked Lists Traversed in either direction Typical operations Initialize the list Destroy the list Determine if list empty Search list for a given
More informationData Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010
Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010 Problem 1. In each of the following question, please specify if the statement
More informationData Structures Chapter 3 Stacks and Queues
Data Structures Chapter 3 Stacks and Queues Instructor: Ching Chi Lin 林 清 池 助 理 教 授 chingchi.lin@gmail.com Department of Computer Science and Engineering National Taiwan Ocean University Outline Stacks
More informationDATA STRUCTURES USING C
DATA STRUCTURES USING C QUESTION BANK UNIT I 1. Define data. 2. Define Entity. 3. Define information. 4. Define Array. 5. Define data structure. 6. Give any two applications of data structures. 7. Give
More informationDATA STRUCTURE - QUEUE
DATA STRUCTURE - QUEUE http://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm Copyright tutorialspoint.com Queue is an abstract data structure, somewhat similar to stack. In contrast to
More informationCommon Data Structures
Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees
More informationDATA STRUCTURE - STACK
DATA STRUCTURE - STACK http://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm Copyright tutorialspoint.com A stack is an abstract data type ADT, commonly used in most programming
More informationChapter 3: Restricted Structures Page 1
Chapter 3: Restricted Structures Page 1 1 2 3 4 5 6 7 8 9 10 Restricted Structures Chapter 3 Overview Of Restricted Structures The two most commonly used restricted structures are Stack and Queue Both
More information10CS35: Data Structures Using C
CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a
More informationStacks. Linear data structures
Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations
More informationPES Institute of Technology-BSC QUESTION BANK
PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions
More informationSt S a t ck a ck nd Qu Q eue 1
Stack and Queue 1 Stack Data structure with Last-In First-Out (LIFO) behavior In Out C B A B C 2 Typical Operations Pop on Stack Push isempty: determines if the stack has no elements isfull: determines
More informationData Structures and Algorithms V22.0102. Otávio Braga
Data Structures and Algorithms V22.0102 Otávio Braga We use a stack When an operand is read, output it When an operator is read Pop until the top of the stack has an element of lower precedence Then push
More informationQUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q
QUEUES A queue is simply a waiting line that grows by adding elements to its end and shrinks by removing elements from the. Compared to stack, it reflects the more commonly used maxim in real-world, namely,
More informationKrishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C
Tutorial#1 Q 1:- Explain the terms data, elementary item, entity, primary key, domain, attribute and information? Also give examples in support of your answer? Q 2:- What is a Data Type? Differentiate
More information7.1 Our Current Model
Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.
More information1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.
1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated
More informationAlgorithms and Data Structures
Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2
More informationCS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A
More informationStack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1
Stack & Queue Explain Array in detail One Dimensional Array Simplest data structure that makes use of computed address to locate its elements is the onedimensional array or vector; number of memory locations
More informationData Structure with C
Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which
More informationIntroduction to Data Structures
Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate
More informationProgramming with Data Structures
Programming with Data Structures CMPSCI 187 Spring 2016 Please find a seat Try to sit close to the center (the room will be pretty full!) Turn off or silence your mobile phone Turn off your other internet-enabled
More informationThe following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).
CHAPTER 5 The Tree Data Model There are many situations in which information has a hierarchical or nested structure like that found in family trees or organization charts. The abstraction that models hierarchical
More information5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.
1. The advantage of.. is that they solve the problem if sequential storage representation. But disadvantage in that is they are sequential lists. [A] Lists [B] Linked Lists [A] Trees [A] Queues 2. The
More informationMAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------
=============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - www.mubashirnabi.com
More informationChapter Objectives. Chapter 7. Stacks. Various Types of Stacks LIFO. Empty Stack. Stacks
Chapter Objectives Chapter 7 Stacks Learn about stacks Examine various stack operations Learn how to implement a stack as an array Learn how to implement a stack as a linked list Discover stack applications
More informationCSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016
CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues Linda Shapiro Registration We have 180 students registered and others who want to get in. If you re thinking of dropping
More informationBoolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
More informationName: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationStacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1
Stacks (and Queues) 1 Stacks Stack: what is it? ADT Applications Implementation(s) 2 CSCU9A3 1 Stacks and ueues A stack is a very important data structure in computing science. A stack is a seuence of
More informationLecture Notes on Linear Search
Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is
More informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationData Structures UNIT III. Model Question Answer
Data Structures UNIT III Model Question Answer Q.1. Define Stack? What are the different primitive operations on Stack? Ans: Stack: A stack is a linear structure in which items may be added or removed
More informationCourse: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1
Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions
More information1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.
Study Group 1 Variables and Types 1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier. 2. What does the byte 00100110 represent? 3. What is the purpose of the declarations
More informationUIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything
More informationAnalysis of a Search Algorithm
CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,
More informationSTACKS,QUEUES, AND LINKED LISTS
STACKS,QUEUES, AND LINKED LISTS Stacks Queues Linked Lists Double-Ended Queues Case Study: A Stock Analysis Applet 1 Stacks Astack is a container of objects that are inserted and removed according to the
More informationCOMPUTER SCIENCE. Paper 1 (THEORY)
COMPUTER SCIENCE Paper 1 (THEORY) (Three hours) Maximum Marks: 70 (Candidates are allowed additional 15 minutes for only reading the paper. They must NOT start writing during this time) -----------------------------------------------------------------------------------------------------------------------
More informationUnit 1. 5. Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]
Unit 1 1. Write the following statements in C : [4] Print the address of a float variable P. Declare and initialize an array to four characters a,b,c,d. 2. Declare a pointer to a function f which accepts
More informationSources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
More informationIntroduction to Stacks
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack. What is a Stack? Stack is a data structure in which data is added
More informationKITES TECHNOLOGY COURSE MODULE (C, C++, DS)
KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL
More informationC++ INTERVIEW QUESTIONS
C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get
More informationList, Stack and Queue. Tom Chao Zhou CSC2100B Data Structures Tutorial 3
List, Stack and Queue Tom Chao Zhou CSC2100B Data Structures Tutorial 3 Outline Structure Linked List Overview Implementation Stack Overview Implementation Queue Overview Implementation Structure A collection
More informationClass Notes CS 3137. 1 Creating and Using a Huffman Code. Ref: Weiss, page 433
Class Notes CS 3137 1 Creating and Using a Huffman Code. Ref: Weiss, page 433 1. FIXED LENGTH CODES: Codes are used to transmit characters over data links. You are probably aware of the ASCII code, a fixed-length
More informationQueues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic
Queues Outline and Required Reading: Queues ( 4. except 4..4) COSC, Fall 3, Section A Instructor: N. Vlajic Queue ADT Queue linear data structure organized according to first-in/first-out (FIFO) principle!
More informationEmbedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C
Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection
More informationData Structures and Data Manipulation
Data Structures and Data Manipulation What the Specification Says: Explain how static data structures may be used to implement dynamic data structures; Describe algorithms for the insertion, retrieval
More informationStacks. Data Structures and Data Types. Collections
Data Structures and Data Types Data types Set values. Set operations on those values. Some are built in to Java: int, double, char,... Most are not: Complex, Picture, Charge, Stack, Queue, Graph,... Data
More informationCOMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012
Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about
More informationJava Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
More informationTREE BASIC TERMINOLOGIES
TREE Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing hierarchical relationship between the grand father and his children and
More information1 Description of The Simpletron
Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies
More informationBSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering
BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security & BSc. (Hons.) Software Engineering Cohort: BIS/05/FT BCNS/05/FT BSE/05/FT Examinations for 2005-2006 / Semester
More informationTranslating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language
Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description
More informationLecture Notes on Stacks & Queues
Lecture Notes on Stacks & Queues 15-122: Principles of Imperative Computation Frank Pfenning, André Platzer, Rob Simmons Lecture 9 February 12, 2013 1 Introduction In this lecture we introduce queues and
More informationThis lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues 1. 2004 Goodrich, Tamassia
This lecture Abstract data types Stacks Queues ADTs, Stacks, Queues 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations
More informationPartitioning under the hood in MySQL 5.5
Partitioning under the hood in MySQL 5.5 Mattias Jonsson, Partitioning developer Mikael Ronström, Partitioning author Who are we? Mikael is a founder of the technology behind NDB
More informationA TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION
A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION Tao Chen 1, Tarek Sobh 2 Abstract -- In this paper, a software application that features the visualization of commonly used
More informationCmpSci 187: Programming with Data Structures Spring 2015
CmpSci 187: Programming with Data Structures Spring 2015 Lecture #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is
More informationOutline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions
More informationSequential Data Structures
Sequential Data Structures In this lecture we introduce the basic data structures for storing sequences of objects. These data structures are based on arrays and linked lists, which you met in first year
More informationPART-A Questions. 2. How does an enumerated statement differ from a typedef statement?
1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members
More informationWhat is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation
Stacks and Queues What is a Stack? Stores a set of elements in a particular order Accessed in Last-In In-First-Out (LIFO) fashion Real life examples: Pile of books PEZ dispenser Cup trays in cafeteria
More informationCS 2412 Data Structures. Chapter 2 Stacks and recursion
CS 2412 Data Structures Chapter 2 Stacks and recursion 1 2.1 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one end, called top of the stack. Examples:
More informationCHAPTER 4 ESSENTIAL DATA STRUCTRURES
CHAPTER 4 ESSENTIAL DATA STRUCTURES 72 CHAPTER 4 ESSENTIAL DATA STRUCTRURES In every algorithm, there is a need to store data. Ranging from storing a single value in a single variable, to more complex
More informationMasters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013
Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper
More informationLast not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!
ECE 551 C++ Programming, Data structures, and Algorithms Abstract Data Type: Stack Last In First Out (LIFO) 1 2 2 1 4 3 1 3 4 Stacks in Programming Worst line ever! 5 3 1 5 Stacks are not useful for waiting
More informationQuestions 1 through 25 are worth 2 points each. Choose one best answer for each.
Questions 1 through 25 are worth 2 points each. Choose one best answer for each. 1. For the singly linked list implementation of the queue, where are the enqueues and dequeues performed? c a. Enqueue in
More informationAtmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : 572365, 576681 1
Data Structure By Ajay Raiyani Yogidham, Kalawad Road, Rajkot. Ph : 572365, 576681 1 Linked List 4 Singly Linked List...4 Doubly Linked List...7 Explain Doubly Linked list: -...7 Circular Singly Linked
More informationLinear ADTs. Restricted Lists. Stacks, Queues. ES 103: Data Structures and Algorithms 2012 Instructor Dr Atul Gupta
Linear DT-1: Restricted Lists Stacks, Queues tul Gupta Restricted Lists Stack Queue Circular queue Priority queue General Lists rrays Linked list Circular list Doubly linked list Linear DTs 1 Stacks Using
More informationBinary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R
Binary Search Trees A Generic Tree Nodes in a binary search tree ( B-S-T) are of the form P parent Key A Satellite data L R B C D E F G H I J The B-S-T has a root node which is the only node whose parent
More informationQueue ADT. March 16, 2000
Queue ADT March 6, 2000 The Queue ADT Queue represent another form of linear data structure. As in the case of the list, the idea of a queue is to represent sequences of elements, all having the same type.
More informationData Structures and Algorithms Stacks and Queues
Data Structures and Algorithms Stacks and Queues Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/23 6-0: Stacks and
More informationIntroduction to Data Structures and Algorithms
Introduction to Data Structures and Algorithms Chapter: Elementary Data Structures(1) Lehrstuhl Informatik 7 (Prof. Dr.-Ing. Reinhard German) Martensstraße 3, 91058 Erlangen Overview on simple data structures
More informationGlossary of Object Oriented Terms
Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction
More informationData Structure [Question Bank]
Unit I (Analysis of Algorithms) 1. What are algorithms and how they are useful? 2. Describe the factor on best algorithms depends on? 3. Differentiate: Correct & Incorrect Algorithms? 4. Write short note:
More informationPROBLEMS (Cap. 4 - Istruzioni macchina)
98 CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS PROBLEMS (Cap. 4 - Istruzioni macchina) 2.1 Represent the decimal values 5, 2, 14, 10, 26, 19, 51, and 43, as signed, 7-bit numbers in the following binary
More informationBasic Data Structures and Algorithms
Tutorial 3 Basic Data Structures and Algorithms THINGS TO LOOK FOR 3.0 INTRODUCTION 3.1 Array Based Containers Definition and uses of containers. Array and list based containers. Designing and building
More informationThis Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers
This Unit: Floating Point Arithmetic CIS 371 Computer Organization and Design Unit 7: Floating Point App App App System software Mem CPU I/O Formats Precision and range IEEE 754 standard Operations Addition
More informationQueues and Stacks. Atul Prakash Downey: Chapter 15 and 16
Queues and Stacks Atul Prakash Downey: Chapter 15 and 16 Queues Queues occur in real life a lot. Queues at checkout Queues in banks In software systems: Queue of requests at a web servers Properties of
More informationLecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists
Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse
More informationCourse: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1
Definition Course: Programming II - Abstract Data Types The ADT Queue The ADT Queue is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit addition
More informationMoving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
More informationA binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:
Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)
More informationPROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks
PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks 1 STACK A structure with a series of data elements with last sent element waiting for a delete operation.
More informationCreating Basic Excel Formulas
Creating Basic Excel Formulas Formulas are equations that perform calculations on values in your worksheet. Depending on how you build a formula in Excel will determine if the answer to your formula automatically
More informationLecture 9. Semantic Analysis Scoping and Symbol Table
Lecture 9. Semantic Analysis Scoping and Symbol Table Wei Le 2015.10 Outline Semantic analysis Scoping The Role of Symbol Table Implementing a Symbol Table Semantic Analysis Parser builds abstract syntax
More informationCompSci-61B, Data Structures Final Exam
Your Name: CompSci-61B, Data Structures Final Exam Your 8-digit Student ID: Your CS61B Class Account Login: This is a final test for mastery of the material covered in our labs, lectures, and readings.
More informationEE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)
EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE) UNIT I LINEAR STRUCTURES Abstract Data Types (ADT) List ADT array-based implementation linked list implementation cursor-based linked lists
More informationExample of a Java program
Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);
More informationChapter 5 Instructor's Manual
The Essentials of Computer Organization and Architecture Linda Null and Julia Lobur Jones and Bartlett Publishers, 2003 Chapter 5 Instructor's Manual Chapter Objectives Chapter 5, A Closer Look at Instruction
More informationReview of Hashing: Integer Keys
CSE 326 Lecture 13: Much ado about Hashing Today s munchies to munch on: Review of Hashing Collision Resolution by: Separate Chaining Open Addressing $ Linear/Quadratic Probing $ Double Hashing Rehashing
More informationAnalysis of Micromouse Maze Solving Algorithms
1 Analysis of Micromouse Maze Solving Algorithms David M. Willardson ECE 557: Learning from Data, Spring 2001 Abstract This project involves a simulation of a mouse that is to find its way through a maze.
More informationClass Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction
Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know
More information