Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

Similar documents
Linked lists * Nguyen Viet Ha, Truong Ninh Thuan, Vu Quang Dung Linked lists

LINKED IMPLEMENTATION OF LIST

Content: Learning Objectives

LINKED LISTS. Abhishek Vashishtha,Deepak Goswami Student, Department of Information, Dronacharya College Of Engineering, Gurgoan, Haryana, India

DEEPIKA KAMBOJ UNIT 2. What is Stack?

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

1 P age DS & OOPS / UNIT II

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues

DATA STRUCTURE UNIT I

Lecture Data Structure Stack

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

Formal Languages and Automata Theory, SS Project (due Week 14)

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Types of Data Structures

DATA STRUCUTRES. A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.

The time and space are the two measure for efficiency of an algorithm.

Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113)

Sample Question Paper

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

CS W3134: Data Structures in Java

infix expressions (review)

Postfix (and prefix) notation

Introduction to Data Structure

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

STACKS AND QUEUES. Problem Solving with Computers-II

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

The Stack and Queue Types

UNIT-II. Part-2: CENTRAL PROCESSING UNIT

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

Insert. SEMCOM Page 1 of 11

INSTITUTE OF AERONAUTICAL ENGINEERING

PA3 Design Specification

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CSE 230 Intermediate Programming in C and C++

DATA STRUCTURES AND ALGORITHMS

Algorithms and Data Structures

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Ashish Gupta, Data JUET, Guna

CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar

Stacks and Queues. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

12 Abstract Data Types

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Stack Abstract Data Type

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

a) State the need of data structure. Write the operations performed using data structures.

3. Fundamental Data Structures

LIFO : Last In First Out

Information Science 2

Lecture 4 Stack and Queue

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT

Prepared by Mrs.D.Maladhy (AP/IT/RGCET) Page 1

17CS33:Data Structures Using C QUESTION BANK

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

Stacks, Queues (cont d)

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

Linked List. April 2, 2007 Programming and Data Structure 1

Advanced Linked Lists. Doubly Linked Lists Circular Linked Lists Multi- Linked Lists

CS 206 Introduction to Computer Science II

CS301 - Data Structures Glossary By

UNIT 3

March 13/2003 Jayakanth Srinivasan,

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

CS8391-DATA STRUCTURES QUESTION BANK UNIT I

CS200: Queues. Prichard Ch. 8. CS200 - Queues 1

Summer Final Exam Review Session August 5, 2009

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Department of Computer Science and Technology

An Introduction to Trees

Linear Data Structure

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)


Adapted By Manik Hosen

Stacks and Queues. CSE Data Structures April 12, 2002

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Lecture No.04. Data Structures

CISC

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

List, Stack, and Queues

CS 8391 DATA STRUCTURES

CSE 214 Computer Science II Stack

CS8391-DATA STRUCTURES

1. Attempt any three of the following: 15

Stacks, Queues and Hierarchical Collections

Fundamentals of Data Structure

R13. II B. Tech I Semester Supplementary Examinations, May/June DATA STRUCTURES (Com. to ECE, CSE, EIE, IT, ECC)

Draw a diagram of an empty circular queue and describe it to the reader.

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

End-Term Examination Second Semester [MCA] MAY-JUNE 2006

Lab 7 1 Due Thu., 6 Apr. 2017

Answers. 1. (A) Attempt any five : 20 Marks

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Data Structures and Algorithms

Transcription:

1. What is the full form of LIFO? The full form of LIFO is Last In First Out. 2. Give some examples for stack application. The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion. 3. Write an algorithm to convert infix to postfix. Algorithm to Convert Infix Expression to Postfix Form. The following algorithm transforms the infix expression X into its equivalent postfix expression Y. The algorithm uses a stack to temporarily hold operators and the left parentheses. The postfix expression Y will be constructed from left to right using operands from X and the operators which are removed from STACK. We begin by pushing a left parenthesis onto STACK and adding a right parenthesis at the end of X. The algorithm is completed when the STACK is empty. ALGORITHM-Infix to Postfix Conversion using Stack. Suppose X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Y. 1. Push "("onto STACK, and add ")" to the end of X. 2. Scan X from left to right and REPEAT Steps 3 to 6 for each element of X. UNTIL the STACK is empty: 3. If an operand is encountered, add it to Y. 4. If a left parenthesis is encountered, push it onto STACK. 5. If an operator is encountered, then: (a) Repeatedly pop from STACK and add to Y each operator (on the top of STACK) which has the same precedence as or a higher precedence than the operator. (b) Add operator to STACK. /* End of if structure */ 6. If a right parenthesis is encountered, then: (a) Repeatedly pop from STACK and add to Y each operator (on the top of STACK) until a left parenthesis is encountered. 1

(b) Remove the left parenthesis. [Do not add the left parenthesis to Y]. /* End of the If structure */ /* End of step 2 loop */ 7. END. 4. Write an algorithm to insert an element into a stack as an array and for linked stack. ALGORITHM- Pushing in Stack-Array /* Assuming that array-stack can hold maximum N elements 1. top = -1 /* Initialize stack with invalid subscript value to show that it is empty. Legal subscript values are 0 (N-1)*/ 2. Read item // Item, which is to be pushed 3. If (top==n-1)then /* if top is at end of stack-array */ 4. Print "Overflow!!" 5. Else 6. top=top+1 /* Increment top to move to next empty position to hold new item */ 7. Stack[top] = Item 8. END. ALGORITHM-Pushing in Linked -Stack /* Get new node for the ITEM to be pushed */ 1. NEWPTR = new Node 2. NEWPTR -> INFO = ITEM ; NEWPTR - > LINK = NULL /*Add new node at the top */ 3. If TOP = NULL then /* stack is empty */ 2

4. TOP = NEWPTR 5. else 6. NEWPTR -> LINK=TOP 7. TOP = NEWPTR // of step 3 8. END. 5. Write an algorithm to insert element into a queue. ALGORITHM - Insertion in Array Queue /* given Rear and Front are pointers to the rear and front of a queueu QUEUE, with size N and an element ITEM is to be inserted into the queue*/ 1. If rear = NULL Then // sets the pointers to 0 because the first element is inserted in the queue 2. Rear = front =0 3. QUEUE[0] = ITEM 4. Else if rear = N-1 Then //checks for overflow 5. Print "QUEUE FULL, OVERFLOW!!" 6. Else 7. QUEUE [rear+1] = ITEM //increments rear pointer and inserts the element 8. rear = rear +1 9. END. 6. Write an algorithm to delete an element from a queue 3

ALGORITHM-Deletion in Array-Queue /* given Rear and Front are pointers to the rear and front of a queue QUEUE, with size N and ITEM is a temporary variable*/ 1. If front = NULL Then // check whether queue is underflow 2. print "Queue Empty" 3. Else 4. ITEM = QUEUE[front] // moves the first element to the temporary variable 5. if front = rear Then //checks whether that is the last element in the queue 6. front = rear = NULL 7. Else 8. front = front + 1 // increments the front pointer 7. Write an algorithm to delete an element from a stack as linked. ALGORITHM-Popping from a Linked-Stack 1. If TOP = NULL then 2. Print "Stack Empty, UNDERFLOW!!" 3. Else 4. Print TOP -> INFO 5. TOP =TOP -> LINK 6. END. 4

8. Change the following from infix to post fix (A+B)*C+D/E-F AB+C*DE/+F- 9. Change the following from infix to post fix A+B-D/X AND (X+Y)/(Z*Y)-R AB+DX/- AND XY+ZY*/R- 10. Change the following from infix to post fix+ ((B+C)+(D+E)*F)/G ABC+DE+F*+G/+ 11. Change the following from infix to post fix A*(B+(C+D)*(E+F)/G)*H ABCD+EF+*G/+*H* 12. Write an algorithm to implement PUSH and POP operation on a stack. /* Assuming that array-stack can hold maximum N elements 1. top = -1 /* Initialize stack with invalid subscript value to show that it is empty. Legal subscript values are 0 (N-1)*/ 2. Read item // Item, which is to be pushed 3. If (top==n-1)then /* if top is at end of stack-array */ 4. Print "Overflow!!" 5. Else 6. top=top+1 /* Increment top to move to next empty position to hold new item */ 7. Stack[top] = Item 8. END. 5

ALGORITHM- Popping from Array-Stack /* Firstly, check for underflow condition */ 1. If top==-1 then 2. Print "Underflow!!" 3. Exit from program 4. Else 5. Print stack(top) 6. top = top +1 /* top moved, so that the top most element becomes */ /* inaccessible which is a sort of a deletion */ 7. END. 13. Write the various applications of stack in detail. Evaluation of a postfix Expression As postfix expression is without parenthesis and can be evaluated as two operands and an operator at a time, this becomes easier for the compiler and the computer to handle. Evaluation rule of a postfix expression states: While reading the expression from left to right, push the element in the stack if it is an operand; pop the two operands from the stack, if the element is an operator (except NOT operator). In case of NOT operators, pop one operand from the stack and then evaluate it (two operands and an operator). Push back the result of the evaluation. Repeat it till the end of the expression. For a binary operator, two operands, one popped from stack and the for a binary operator, one operand is popped. Then, the result is calculated using operand(s) and the operator, and pushed back into the stack. Polish Strings Another application of stacks is in the conversion of arithmetic expression in high-level programming languages into machine readable form. As our computer system can only understand and work on a binary language, it assumes that an arithmetic operation can take place in two operands only, e.g., A+B, CXD, D/A, etc. But in our usual form - an arithmetic expression may consist of more than one operators and two operands, e.g., (A+B) X C (D/(J+D)). These complex arithmetic operations can be 6

converted into polish strings using stacks which can be executed in two operands and an operator form. Polish string, named after a polish mathematician, Jan Lukasiewicz, refers to the notation in which the operator symbol is placed either before its operands (prefix notation) or after its operands (postfix notation) in contrast to the usual form where operator is placed in-between the operands (infix notation). The following table shows three types of notations: 14. Write algorithms to implement operations on a circular queue. Queues can be used in several forms and ways, depending upon the requirements of the program. Two popular variations of queues are circular queues and dequeues (double ended queues). Circular Queues are the queues implemented in a circular form rather than a straight line. Circular queues overcome the problem of unutilized space in linear queues implemented as arrays (if shifting is not done to avoid the problem of unutilized space, but shifting as such makes it complex to implement). We saw that queues don t effectively use the memory. To overcome this, we have designed the circular queues. It uses array as a circular structure. If the rear point of the queue reaches the end of the array, we can add a new element at the beginning of the array if it is vacant. One should keep in mind that it does not spoil the operations of a queue. This is achieved by using the front and rear pointers effectively. front = 3 0 1 2 3 4 5 N-2 N- 1 rear = N-2 25 17 12 5 (a) Queue at any arbitrary point of line front = 3 0 1 2 3 4 5 N-2 N- 1 rear = N-1 25 17 12 5 7 (b) One element inserted front = 4 0 1 2 3 4 5 N-2 N- 1 rear = N-1 17 12 5 7 (c) One element deleted front = 4 0 1 2 3 4 5 N-2 N- 1 rear = 0 9 17 12 5 7 (d) One more element inserted [The circular queue considers itself contiguous at opposite ends, that is why, if space is there in the beginning, the rear shifts back to beginning after reaching the maximum possible index-number.] 7

Fig. (a) operations in a circular queue implemented as an array. Fig. (b) A Circular Queue. Deque (double-ended queues) are the refined queues in which elements can be added or removed at either end but not in the middle. There are two variation of a deque an input restricted deque and an output restricted deque. An input restricted deque is a deque which allows insertions at only one end but allows deletions at both ends of the list. An output restricted deque is a deque which allows deletion at only one end of the list but allows insertions at both ends of the list. Algorithm-Insertion in a Circular Queue /* Assuming that the circular queues is stored in QU with size N. Check if Queue already filled or not */ 1. If (FRONT = AND REAR = N- 1) or (FRONT = REAR +1) Then Write " Overflow!!" Else 2. If FRONT = NULL Then [QU is initially empty] Set FRONT = 0 REAR = 0 8

3. Else IF REAR = N-1 Then Set REAR = 0 Else 4. Set REAR = REAR +1 //End of if 5. Set QU [REAR] = I_ITEM // (to insert the new item I_ITEM 6. END. Algorithm-Deletion in a circular Queue. /* Assuming that the queue is stored in as array QU with size N. This algorithm will delete an element from the queue and assign it to D-ITEM. */ /* Check if QU is already empty or not? */ 1. If FRONT = NULL Then Write " Underflow!!" Return Else 2. Set D_ITEM = QU[FRONT] /* Now Make FRONT point to the next element in the queue */ 3. If FRONT = REAR Then FRONT = NULL REAR = NULL 9

4. Else If FRONT = N-1 Then FRONT = 0 Else 5. FRONT = FRONT +1 6. END. 15. What are the various operations on a linked list? When manipulating linked lists in-place, care must be taken to not use values that you have invalidated in previous assignments. This makes algorithms for inserting or deleting linked list nodes which are somewhat subtle. This section gives pseudo code for adding or removing nodes from singly, doubly, and circularly linked lists in-place. Throughout, we will use null to refer to an end-oflist marker which may be implemented in a number of ways. Traversal Our node data structure will have two fields. We also keep a variable firstnode which always points to the first node in the list, or is null for an empty list. record Node data // The data being stored in the node next // A reference to the next node, null for last node record List Node firstnode // points to first node of list; null for empty list Traversal of a singly-linked list is simple, beginning at the first node and following each next link until we come to the end: node := list.firstnode while node not null (do something with node.data) node := node.next 10

Insertion The following code inserts a node after an existing node in a singly linked list. The diagram shows how it works. Inserting a node before an existing one cannot be done; instead, you have to locate it while keeping track of the previous node. function insertafter(node node, Node newnode) // insert newnode after node newnode.next := node.next node.next := newnode Inserting at the beginning of the list requires a separate function. This requires updating firstnode. function insertbeginning(list list, Node newnode) // insert node before current first node newnode.next := list.firstnode list.firstnode := newnode Deletion Similarly, we have functions for removing the node after a given node, and for removing a node from the beginning of the list. The diagram demonstrates the former. To find and remove a particular node, one must again keep track of the previous element. 11

function removeafter(node node) // remove node past this one obsoletenode := node.next node.next := node.next.next destroy obsoletenode function removebeginning(list list) // remove first node obsoletenode := list.firstnode list.firstnode := list.firstnode.next // point past deleted node destroy obsoletenode Notice that removebeginning() sets list.firstnode to null when removing the last node in the list. Since we can't iterate backwards, efficient "insertbefore" or "removebefore" operations are not possible. Appending one linked list to another can be inefficient unless a reference to the tail is kept as part of the List structure, because we must traverse the entire first list in order to find the tail, and then append the second list to this. Thus, if two linearly-linked lists are each of length n, list appending has asymptotic time complexity of O(n). In the Lisp family of languages, list appending is provided by the append procedure. Many of the special cases of linked list operations can be eliminated by including a dummy element at the front of the list. This ensures that there are no special cases for the beginning of the list and renders both insertbeginning() and removebeginning() unnecessary. In this case, the first useful data in the list will be found at list.firstnode.next. 16. Differentiate singly linked list vs array. Array Linked list Elements can be inserted into While an array will eventually linked lists indefinitely. either fill up or need to be esized, an expensive operation that may not even be possible if memory is fragmented. Memory savings can be achieved. Similarly, an array from which many elements are removed may become wastefully mpty or need to be made smaller. While linked lists allow only Arrays allow random access. sequential access to elements. Singly-linked lists, in fact, can only Arrays can be traversed in be traversed in one direction. both the directions. 12

A disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or Boolean values. Bad Sequential access on arrays is also faster than on linked lists on many machines due to locality of reference and data cache. 17. What are the trade-offs of a linked list. As with most choices in computer programming and design, no method is well suited to all circumstances. A linked list data structure might work well in one case but causes problems in another. This is a list of some of the common trade-offs involving linked list structures. In general, if you have a dynamic collection, where elements are frequently being added and deleted, and the location of new elements added to the list is significant, then benefits of a linked list increase. 18. How is a linked list represented in memory. Let list be implemented in memory in the simplest form of implementation. LIST requires two linear arrays one called as INFO array for INFO storage and the other known as LINK array for the next pointer. 19. Write a short note on static and dynamic memory allocation. Static memory allocation This memory allocation method reserves a fixed amount before the actual processing takes place. The number of elements to be stored is predefined. Arrays the memory is allocated using this technique. Dynamic memory allocation This memory allocation method allows allocation of memory during the program execution itself, as and when required. This technique of memory allocation is called as dynamic memory allocation. This facilitates release of memory. (Data structures like linked lists and tree use this technique. Please rephrase the sentence!) 20. How do you traverse a linked list? 13

Our node data structure will have two fields. We also keep a variable firstnode which always points to the first node in the list, or is null for an empty list. record Node data next // The data being stored in the node // A reference to the next node, null for last node record List Node firstnode // points to first node of list; null for empty list Traversal of a singly-linked list is simple, beginning at the first node and following each next link until we come to the end: node := list.firstnode while node not null (do something with node.data) node := node.next 21. What is the procedure to insert an element in a linked list? The following code inserts a node after an existing node in a singly linked list. The diagram shows how it works. Inserting a node before an existing one cannot be done; instead, you have to locate it while keeping track of the previous node. function insertafter(node node, Node newnode) // insert newnode after node 14

newnode.next := node.next node.next := newnode Inserting at the beginning of the list requires a separate function. This requires updating the firstnode. function insertbeginning(list list, Node newnode) // insert node before current first node newnode.next := list.firstnode list.firstnode := newnode 22. Write short notes on polish strings. Another application of stacks is in the conversion of arithmetic expression in high-level programming languages into machine readable form. As our computer system can only understand and work on a binary language, it assumes that an arithmetic operation can take place in two operands only, e.g. A+B, CXD, D/A, etc. But in our usual form an arithmetic expression may consist of more than one operators and two operands, e.g., (A+B) X C (D/(J+D)). These complex arithmetic operations can be converted into polish strings using stacks which can be executed in two operands and an operator form. The polish string, named after a polish mathematician, Jan Lukasiewicz, refers to the notation in which the operator symbol is placed either before its operands (prefix notation) or after its operands (postfix notation) in contrast to the usual form where operator is placed in-between the operands (infix notation). The following table shows the three types of notations: Notation Infix Prefix Postfix Example A+B +AB AB+ 23. State the advantages of postfix over infix expression. An infix expression is difficult for the machine to know and keep track of precedence of operators. On the other hand, a postfix expression itself determines the precedence of operators (as the placement of operators in a postfix expression depends upon its precedence). Therefore, for the machine it is easier to carry out a postfix expression than an infix expression. 24. Write a short note on queue. A queue is an ordered group of elements in which new elements are added at one end and the elements are removed at the other end. The insertion end is called the rear and the deletion end is called the front. 15

Example: Line of viewers in a theatre s ticket counter. New person will join at the end while people who got their tickets will leave the counter at the front. This works on a first-come first-served basis (FCFS). The main thing is that it performs insertion at one end and deletion at the other end. Logically, a queue is a FIFO structure and physically it can be implemented either as an array or as a linked list. Whatever way a queue is implemented, insertions take place at the "rear" end and deletions at the "front" end. 16