Subject Name: DATA STURCTURES WITH C Subject Code: 10CS35

Slides:



Advertisements
Similar presentations
§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
Advertisements

Bioinformatics Programming
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks Chapter 11.
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
CSCE 3110 Data Structures & Algorithm Analysis Queues Reading: Chap. 3 Weiss.
CHAPTER 31 STACKS AND QUEUES. CHAPTER 32 A BABA DCBADCBA CBACBA DCBADCBA EDCBAEDCBA top *Figure 3.1: Inserting and deleting elements in a stack (p.102)
Data Structure Dr. Mohamed Khafagy.
A stack is a data linear data structure in which addition of new element or deletion of an existing element always takes place at the same end. This.
Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.
 Balancing Symbols 3. Applications
CS 206 Introduction to Computer Science II 03 / 06 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 10 / 17 / 2008 Instructor: Michael Eckmann.
Lecture 8 Feb 19 Goals: l applications of stack l Postfix expression evaluation l Convert infix to postfix l possibly start discussing queue.
CHAPTER 31 STACKS AND QUEUES All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of Data.
CS 206 Introduction to Computer Science II 03 / 16 / 2009 Instructor: Michael Eckmann.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
CH3 Stacks and Queues Instructors: C. Y. Tang and J. S. Roger Jang All the material are integrated from the textbook "Fundamentals of Data Structures in.
CS Data Structures Chapter 3 Stacks and Queues.
CS 206 Introduction to Computer Science II 10 / 28 / 2009 Instructor: Michael Eckmann.
Chapter 3 Stacks and Queues  The Stack Abstract Data Type  The Queue Abstract Data Type  A Mazing Problem  Evaluation of Expressions.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Data Structures Week 4 Our First Data Structure The story so far  We understand the notion of an abstract data type.  Saw some fundamental operations.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Chapter 18: Stacks and Queues
1 Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
杭州师范大学信息科学与工程学院 袁贞明 STACKS AND QUEUES and their applications.
CHP-3 STACKS.
Chapter 17: Stacks and Queues. Objectives In this chapter, you will: – Learn about stacks – Examine various stack operations – Learn how to implement.
Been-Chian Chien, Wei-Pang Yang and Wen-Yang Lin 3-1 Chapter 3 Stacks and Queues Introduction to Data Structures CHAPTER 3 STACKS and QUEUES 3.1 The Stack.
CSCE 3110 Data Structures & Algorithm Analysis Rada Mihalcea Stack Applications Reading: Chap. 3 Weiss.
Stacks Objective After this lecture you will be able to: Describe a stack Describe the representation of stack using linear array Describe the representation.
STACKS AND QUEUES.
CSCE 3110 Data Structures & Algorithm Analysis
Chapter 4 Stacks
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Review Array Array Elements Accessing array elements
Stacks.
Data Structures Using C, 2e
Queues.
UNIT II Queue.
Stacks Stacks.
Data Structures 5th Week
CS 201 Data Structures and Algorithms
Queues Queues Queues.
Stacks.
CSCE 3110 Data Structures & Algorithm Analysis
Stacks Chapter 4.
Data Structures – Week #3
Algorithms and Data Structures
CSCE 3110 Data Structures & Algorithm Analysis
Stack Data Structure, Reverse Polish Notation, Homework 7
Stacks and Queues The Stack abstract data type
CSCE 3110 Data Structures & Algorithm Analysis
Stacks Chapter 5 Adapted from Pearson Education, Inc.
UNIT-I Topics to be covere d 1.Introduction to data structures.
پشته ها و صف ها.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
CSCE 3110 Data Structures & Algorithm Analysis
CE 221 Data Structures and Algorithms
Stack.
Data Structures – Week #3
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Presentation transcript:

Subject Name: DATA STURCTURES WITH C Subject Code: 10CS35 Prepared By: AMBIKA NITHENDRA MAHAJAN Department: ISE Date: 12/08/14 11/12/2018

Inserting and deleting elements in a stack A B C D E CHAPTER 3 STACKS AND QUEUES Two of the more common data objects found in computer algorithms are stacks and queues. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. The restrictions on a stack imply that if the elements A,B,C,D,E are added to the stack, in that order, then the first element to be removed/deleted must be E. Equivalently we say that the last"element to be inserted into the stack will be the first to be removed. For this reason stacks are sometimes referred to as Last In First Out (LIFO) lists. illustration Inserting and deleting elements in a stack A B C D E top 11/12/2018

Some stack applications Implementing recursive calls Expression evaluation - evaluation of postfix expression Conversion of expressions Infix to postfix Postfix to infix Maze problem Breadth First Search 11/12/2018

Abstract data type for stack structure Stack 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 Add(stack, item) ::= if (IsFull(stack)) stack_full else insert item into top of stack and return 11/12/2018

Boolean IsEmpty(stack) ::= Boolean IsEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSE Element Delete(stack) ::= if(IsEmpty(stack)) return else remove and return the item on the top of the stack. ADT : Abstract data type Stack 11/12/2018

Array-based Stack Implementation Allocate an array of some size (pre-defined) Maximum N elements in stack Bottom stack element stored at element 0 last index in the array is the top Increment top when one element is pushed, decrement after pop 11/12/2018

Implementation: using array Stack CreateS(max_stack_size) ::= #define MAX_STACK_SIZE 100 /* maximum stack size */ typedef struct { int key; /* other fields */ } element; element stack[MAX_STACK_SIZE]; int top = -1; Boolean IsEmpty(Stack) ::= top< 0; Boolean IsFull(Stack) ::= top >= MAX_STACK_SIZE-1; 11/12/2018

Push operation void push(int *top, element item) { if (*top >= MAX_STACK_SIZE-1) { stack_full( ); return; } stack[++*top] = item; } program : Add to a stack . 11/12/2018

Pop operation element pop(int *top) { if (*top == -1) return stack_empty( ); /* returns and error key */ return stack[(*top)--]; } Program : Delete from a stack . 11/12/2018

Queue (Queue: a First-In-First-Out (FIFO) list) Queue is an ordered list in which all insertions take place at one end, the rear, while all deletions take place at the other end, the front. The restrictions on a queue require that the first element which is inserted into the queue will be the first one to be removed. Thus A is the first letter to be removed, and queues are known as First In First Out (FIFO) lists. The first element inserted is the first one to be removed The most common occurrence of a queue in computer applications is for the scheduling of jobs The first one in line is the first one to be served 11/12/2018

Applications related to Computer Science Threads Real life examples Waiting in line Ticket Counter Applications related to Computer Science Threads Job scheduling (e.g. Round-Robin algorithm for CPU allocation) Queue: a First-In-First-Out (FIFO) list 11/12/2018

Abstract data type of queue structure Queue 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 Queue AddQ(queue, item) ::= 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 return FALSE Element DeleteQ(queue) ::= if (IsEmptyQ(queue)) return else remove and return the item at front of queue. 11/12/2018

Implementation 1: using array 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 11/12/2018

Insert operation void addq(int *rear, element item) { /* add an item to the queue */ if (*rear == MAX_QUEUE_SIZE_1) { queue_full( ); return; } queue [++*rear] = item; } 11/12/2018

Regard an array as a circular queue Delete from a queue Implementation 2: Regard an array as a circular queue A more efficient queue representation is obtained by regarding the array Q(1:n) as circular. It now becomes more convenient to declare the array as Q(0:n - 1). When rear = n - 1, the next element is entered at Q(0) in case that spot is free. front will always point one position counterclockwise from the first element in the queue front: one position counterclockwise from the first element rear: current end element deleteq(int *front, int rear) { /* remove element at the front of the queue */ if ( *front == rear) return queue_empty( ); /* return an error key */ return queue [++ *front]; } 11/12/2018

Figure : Empty and nonempty circular queues 11/12/2018

Problem: one space is left when queue is full Figure : Full circular queues and then we remove the item 11/12/2018

Add to a circular queue void addq (int front, int *rear, element item) { *rear = (*rear +1) % MAX_QUEUE_SIZE; if (front == *rear) /* reset rear and print error */ return; } queue[*rear] = item; } 11/12/2018

Delete from a circular queue element deleteq(int* front, int rear) { element item; if (*front == rear) return queue_empty( ); /* queue_empty returns an error key */ * front = (*front+1) % MAX_QUEUE_SIZE; return queue[*front]; } 11/12/2018

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. 11/12/2018

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. 11/12/2018

A Mazing Problem Figure : An example maze 11/12/2018

Representation A Mazing Problem Figure : Allowable moves 11/12/2018

Implementation A Mazing Problem typedef struct { short int vert; short int horiz; } offsets; offsets move[8]; /*array of moves for each direction*/ 11/12/2018

Use stack to keep 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]; 11/12/2018

Initialize a stack to the maze’s entrance coordinates and direction to north while (stack is not empty) { /* move to position at top of stack */ <row, col, dir> = delete from top of stack; while (there are more moves from current position) { <next_row, next_col > = coordinates of next move; dir = direction of move; if ((next_row == EXIT_ROW)&& (next_col == EXIT_COL)) success; if (maze[next_row][next_col] == 0 && mark[next_row][next_col] == 0) { 11/12/2018

/* legal move and haven’t been there */ mark[next_row][next_col] = 1; /* save current position and direction */ add <row, col, dir> to the top of the stack; row = next_row; col = next_col; dir = north; } } } printf (“No path found\n”); Program : Initial maze algorithm 11/12/2018

Figure : Simple maze with a long path 11/12/2018

Maze search function void path (void) { /* output a path through the maze if such a path exists */ int i, row, col, next_row, next_col, dir, found = FALSE; element position;mark[1][1] = 1; top =0; stack[0].row = 1; stack[0].col = 1; stack[0].dir = 1; while (top > -1 && !found) { position = delete(&top); row = position.row; col = position.col; dir = position.dir; while (dir < 8 && !found) { /*move in direction dir */ next_row = row + move[dir].vert; next_col = col + move[dir].horiz; 7 N 1 6 W E 2 5 S 3 4 11/12/2018

if (next_row==EXIT_ROW && next_col==EXIT_COL) found = TRUE; else if ( if (next_row==EXIT_ROW && next_col==EXIT_COL) found = TRUE; else if ( !maze[next_row][next_col] && !mark[next_row][next_col] { mark[next_row][next_col] = 1; position.row = row; position.col = col; position.dir = ++dir; add(&top, position); row = next_row; col = next_col; dir = 0; } else ++dir; } } 11/12/2018

if (found) { printf(“The path is :\n”); printf(“row col\n”); for (i = 0; i <= top; i++) printf(“ %2d%5d”, stack[i].row, stack[i].col); printf(“%2d%5d\n”, row, col); printf(“%2d%5d\n”, EXIT_ROW, EXIT_COL); } else printf(“The maze does not have a path\n”); } Program :Maze search function 11/12/2018

Evaluation of Expressions An expression is made up of operands, operators and delimiters. X = a / b - c + d * e - a * c a = 4, b = c = 2, d = e = 3 Interpretation 1:((4/2)-2)+(3*3)-(4*2)=0 + 8+9=1 Interpretation 2:(4/(2-2+3))*(3-4)*2=(4/3)*(-1)*2=-2.66666… The first problem with understanding the meaning of an expression is to decide in what order the operations are carried out. To fix the order of evaluation, we assign to each operator a priority. Then within any pair of parentheses we understand that operators with the highest priority will be evaluated first. 11/12/2018

11/12/2018

11/12/2018

Figure : Precedence hierarchy for C 11/12/2018

Figure : Infix and postfix notation 11/12/2018

Figure : Postfix evaluation 11/12/2018

Algorithm to convert infix To postfix #define MAX_STACK_SIZE 100 /* maximum stack size */ #define MAX_EXPR_SIZE 100 /* max size of expression */ typedef enum{1paran, rparen, plus, minus, times, divide, mod, eos, operand} precedence; int stack[MAX_STACK_SIZE]; /* global stack */ char expr[MAX_EXPR_SIZE]; /* input string */ 11/12/2018

{ if (token == operand) add(&top, symbol-’0’); /* stack insert */ Int eval(void) { /* evaluate a postfix expression, expr, maintained as a global variable, ‘\0’ is the the end of the expression. The stack and top of the stack are global variables. get_token is used to return the token type and the character symbol. Operands are assumed to be single character digits */ precedence token; char symbol; int op1, op2; int n = 0; /* counter for the expression string */ int top = -1; token = get_token(&symbol, &n); while (token != eos) { if (token == operand) add(&top, symbol-’0’); /* stack insert */ 11/12/2018

else { /* remove two operands, perform operation, and return result to the stack */ op2 = delete(&top); /* stack delete */ op1 = delete(&top); switch(token) { case plus: add(&top, op1+op2); break; case minus: add(&top, op1-op2); break; case times: add(&top, op1*op2); break; case divide: add(&top, op1/op2); break; case mod: add(&top, op1%op2); } } token = get_token (&symbol, &n); } return delete(&top); /* return result */ } 11/12/2018

precedence get_token(char. symbol, int. n) {. / precedence get_token(char *symbol, int *n) { /* get the next token, symbol is the character representation, which is returned, the token is represented by its enumerated value, which is returned in the function name */ *symbol =expr[(*n)++]; switch (*symbol) { case ‘(‘ : return lparen; case ’)’ : return rparen; case ‘+’: return plus; case ‘-’ : return minus; 11/12/2018

case ‘/’ : return divide; case ‘ case ‘/’ : return divide; case ‘*’ : return times; case ‘%’ : return mod; case ‘\0‘ : return eos; default : return operand; /* no error checking, default is operand */ } } 11/12/2018

Infix to Postfix Conversion (1) Fully parenthesize expression a / b - c + d * e - a * c --> ((((a / b) - c) + (d * e)) - a * c)) (2) All operators replace their corresponding right parentheses. (3) Delete all parentheses. ab/c-de*+ac*- 11/12/2018

The orders of operands in infix and postfix are the same. a + b * c, * > + Figure : Translation of a+b*c to postfix 11/12/2018

The orders of operands in infix and postfix are the same. Rules The orders of operands in infix and postfix are the same. a + b * c, * > + (1)Operators are taken out of the stack as long as their in-stack precedence(isp) is higher than or equal to the incoming precedence (icp)of the new operator. (2)’(‘ has low in-stack precedence, and high incoming precedence. 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 store them in a stack until just the right moment and then to unstack and pass them to the output. 11/12/2018

Function to convert from infix to postfix void postfix(void) { /* output the postfix of the expression. The expression string, the stack, and top are global */ char symbol; precedence token; int n = 0; int top = 0; /* place eos on stack */ 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 ){ Function to convert from infix to postfix 11/12/2018

/. unstack tokens until left parenthesis. / while (stack[top] /*unstack tokens until left parenthesis */ while (stack[top] != lparen) print_token(delete(&top)); delete(&top); /*discard the left parenthesis */ } else{ /* remove and print symbols whose isp is greater than or equal to the current token’s icp */ while(isp[stack[top]] >= icp[token] ) print_token(delete(&top)); add(&top, token); } } while ((token = delete(&top)) != eos) print_token(token); print(“\n”); } 11/12/2018

Figure : Infix and postfix expressions 11/12/2018

Multiple stacks and queues Two stacks m[0], m[1], …, m[n-2], m[n-1] bottommost bottommost stack 1 stack 2 More than two stacks (n) memory is divided into n equal segments boundary[stack_no] 0  stack_no < MAX_STACKS top[stack_no] 11/12/2018

Initially, boundary[i]=top[i]. Initial configuration for n stacks in memory Initially, boundary[i]=top[i]. 0 1 [ m/n ] 2[ m/n ] m-1 boundary[ 0] boundary[1] boundary[ 2] boundary[n] top[ 0] top[ 1] top[ 2] All stacks are empty and divided into roughly equal segments. 11/12/2018

#define MEMORY_SIZE 100 /. size of memory #define MEMORY_SIZE 100 /* size of memory */ #define MAX_STACK_SIZE 100 /* max number of stacks plus 1 */ /* global memory declaration */ element memory[MEMORY_SIZE]; int top[MAX_STACKS]; int boundary[MAX_STACKS]; int n; /* number of stacks entered by the user */ top[0] = boundary[0] = -1; for (i = 1; i < n; i++) top[i] =boundary[i] =(MEMORY_SIZE/n)*i; boundary[n] = MEMORY_SIZE-1; 11/12/2018

void add(int i, element item) { /. add an item to the ith stack void add(int i, element item) { /* add an item to the ith stack */ if (top[i] == boundary [i+1]) stack_full(i); may have unused storage memory[++top[i]] = item; } Program :Add an item to the stack stack-no element delete(int i) { /* remove top element from the ith stack */ if (top[i] == boundary[i]) return stack_empty(i); return memory[top[i]--]; } Program :Delete an item from the stack stack-no 11/12/2018

Find j, stack_no < j < n such that top[j] < boundary[j+1] or, 0  j < stack_no b[0] t[0] b[1] t[1] b[i] t[i] t[i+1] t[j] b[j+1] b[n] b[i+1] b[i+2] b=boundary, t=top Figure : Configuration when stack i meets stack i+1, but the memory is not full 11/12/2018

References Text Book “Fundamentals of Data Structures in c” by Sahni, 2nd edition. 11/12/2018