0% found this document useful (0 votes)
8 views

Lecture 6 - Stack

asd

Uploaded by

toprakcihalil0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 6 - Stack

asd

Uploaded by

toprakcihalil0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

SE 2005

DATA
STRUCTURES
STACK
• Stack is a linear data structure (container)
– follows a particular order (Last-in-first-out - LIFO) in which
the operations (insertion/delation) are performed.

• Stack can be implemented as a constrained version of a linked list,


because it allows all data operations at one end only (top)
– Unlike linked lists, new nodes can be added to a stack and removed from a
stack only at the top.
– In linked lists, insertions and deletions may occur anywhere.
REAL LIFE

piles of books or dinner plates

COMPUTER
• Page-visited history in a Web browser
• Undo sequence in a text editor
SCIENCE • Saving local variables when one function
calls another, and this one calls another
Insert (Push) and delete (Pop)
operations take place at the same end

Stack Stack Stack

last-in–first-out (LIFO)
BASIC OPERATIONS
• push() − Inserting an element in the stack. The new element is inserted
at the top of the stack.
• pop() − Removing (accessing) an element from the stack. There’s only
one element that we can remove.
• peek() [top ()]− Get the top data element of the stack, without
removing it.
• isEmpty() − Check if the stack is empty or not. It conventionally
returns a boolean value (1 or 0):
• isFull() − opposite of isEmpty().
EXERCISE
• Describe the output of the following series of stack operations
– Push(8)
– Push(3)
– Pop()
– Push(2)
– Push(5) 1
– Pop() 9

– Pop() 8
– Push(9)
– Push(1)
IMPLEMENTATION OF STACK
• There are two ways to implement a stack:
– Static Stack: Using array
• Fixed size stack
– If the stack is full and does not contain enought space for push
operation, the stack is then considered to be in an overflow
state.
• Item, top

– Dynamic Stack: Using linked list


• Newer become full
• Node: data, link
• Stack header
ARRAY IMPLEMENTATION OF STACK
• The first element of the stack (i.e. bottom-most element), is stored at
0'th index in the array (assuming a zero-based indexing).

struct Stack {
int top;
unsigned capacity;
int* array;
};
ARRAY IMPLEMENTATION OF STACK
Define a one dimensional array of specific size and insert/delete the values
into/from that array by using LIFO principle with the help of a variable
called 'top’.
1. If the stack empty, the top is set to -1.
2. Whenever we want to insert a value into the stack, increment the top
value by one and then insert.
3. Whenever we want to delete a value from the stack, then delete the
top value and decrement the top value by one.
ALGORITHMS
FOR PUSH AND
POP
OPERATIONS
If the stack is full, we
cannot push a new
item according to this
example.

What can we do to
add a new item?
İf the stack (array capacity) is full
instead of throwing an exception, we can replace the array with
a larger one

if (isFull(stack)) {
//Step 1
int *array2 = (int *) malloc(sizeof(int)* stack->capacity*2);
3 //Step 2
2
for(i =0; i<stack->capacity; i++)
array2[i] = stack->array[i];
1
//Step 3
free(stack->array);
stack->array = array2;
stack->capacity *= 2;
}
İf the stack (array capacity) becomes less by popping some elements,
we need to decrease the size of array.

X X X X X X

if(stack->top <= stack->capacity/4) {


int *array2 = (int *) malloc(sizeof(int)* stack->capacity/2);

for(i =0; i<stack->top; i++)


array2[i] = stack->array[i];

free(stack->array);
stack->array = array2;
stack->capacity /= 2;
}
SIMULATION FOR ARRAY
IMPLEMENTATION
• https://www.cs.usfca.edu/~galles/visualization/StackArray.html
LINKED LIST IMPLEMENTATION OF
STACK
There are two ends of a linked list: head and tail.

Which end do you think should represent


the top of the stack?

The top of the stack should be represented by head

WHY?
LINKED LIST IMPLEMENTATION OF STACK

Removing an element at
the start is constant time
but
removal at the end
required traversing the
list to the node one
before the last
LINKED LIST IMPLEMENTATION OF STACK
The top node in the stack
always contains null in its
address field.

// Declare linked list node


struct Node {
int data;
struct Node* link;
};

struct Node* top;


ALGORITHMS
FOR PUSH AND
POP
OPERATIONS
SIMULATION FOR LINKED LIST
IMPLEMENTATION
• https://www.cs.usfca.edu/~galles/visualization/StackLL.html
APPLICATIONS OF STACK
• The simplest application of a stack is to reverse a word.
• Evaluation of Arithmetic expressions.
• An "undo" mechanism in text editors
• Forward and backward feature in web browsers
• Tracking function calls
• Towers of Hanoi
• Etc.
REVERSE A WORD
(USING ARRAY IMPLEMENRTATION)
void push(struct Stack* stack, char item) { void reverse(char str[])
if (isFull(stack)) {
return; // Create a stack of capacity equal to length
stack->array[++stack->top] = item; of string
} int n = strlen(str);
struct Stack* stack = createStack(n);
char pop(struct Stack* stack) {
if (isEmpty(stack)) // Push all characters of string to stack
return; int i;
return stack->array[stack->top--]; for (i = 0; i < n; i++)
} push(stack, str[i]);

// Pop all characters of string and put them


back to str
for (i = 0; i < n; i++)
str[i] = pop(stack);
}

For more example  https://www.geeksforgeeks.org/reverse-a-string/


BALANCING SYMBOLS
http://xkcd.com/859/

• Compiler checks for program Algorithm:


• Declare a character stack S.
syntax errors.
• Now traverse the expression string exp.
• If the current character is a starting
• Every right brace, bracket, and bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to
parenthesis must correspond to stack.
• If the current character is a closing
its left counterpart bracket (‘)’ or ‘}’ or ‘]’) then pop from
stack and if the popped character is
the matching starting bracket then fine
• The sequence [()] is legal, but [(]) else brackets are not balanced.
is wrong
• After complete traversal, if there is some
starting bracket left in stack then “not
balanced”
bool isMatchingPair(char character1, char character2) // If exp[i] is an ending bracket then pop from stack and
{ check if the popped bracket is a matching pair*/
if (character1 == '(' && character2 == ')') if (exp[i] == '}' || exp[i] == ')'|| exp[i] == ']') {
return 1;
else if (character1 == '{' && character2 == '}') if (stack == NULL)
return 1; return 0;
else if (character1 == '[' && character2 == ']')
return 1; // Pop the top element from stack, if it is not a
else pair bracket of character then there is a mismatch.
return 0; else if (!isMatchingPair(pop(&stack), exp[i]))
} return 0;
}
bool areBracketsBalanced(char exp[]) i++;
{ }
int i = 0;
struct sNode* stack = NULL; // If there is something left in expression then there is
a starting bracket without a closing bracket
// Traverse the given expression to check matching if (stack == NULL)
brackets return 1; // balanced
while (exp[i]) else
{ return 0; // not balanced
// If the exp[i] is a starting bracket then push it }
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
CONVERSION OF ARITHMETIC EXPRESSIONS
• 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, C*D,D/A etc.

• But in our usual form an arithmetic expression may consist of more than one
operator and two operands
– e.g. (A+B)*C(D/(J+D)).

• These complex arithmetic operations can be converted into polish notation


using stacks which then can be executed in two operands and an operator form.
POLISH NOTATION
• Notation: The way to write arithmetic expression
• An arithmetic expression can be written in three different notations
– Infix Notation: where operators are used in-between operands. It is easy for us
humans to read, write, and speak in infix notation but the same does not go well with
computing devices. An algorithm to process infix notation could be difficult and costly
in terms of time and space consumption. For example, a + b
– Prefix (Polish) Notation: operator is prefixed to operands, i.e. operator is written
ahead of operands. For example, +ab.
– Postfix (Reverse-Polish) Notation: In this notation style, the operator is postfixed
to the operands i.e., the operator is written after the operands. For example, ab+.
INFIX TO POSTFIX CONVERSION
• The compiler scans the expression either from left to right or from right to
left.

• Consider the expression: a + b * c + d


– The compiler first scans the expression to evaluate the expression b * c, then
again scan the expression to add a to it. The result is then added to d after
another scan.
– The repeated scanning makes it very in-efficient. It is better to convert the
expression to postfix(or prefix) form before evaluation.
INFIX TO POSTFIX CONVERSION
Algorithm
1. First Start scanning the expression from left to right
2. If the scanned character is an operand, output it, i.e. print it
3. Else
1. If the precedence of the scanned operator is higher than the precedence of the
operator in the stack(or stack is empty or has'(‘), then push operator in the stack
2. Else, Pop all the operators, that have greater or equal precedence than the scanned
operator. Once you pop them push this scanned operator. (If we see a parenthesis
while popping then stop and push scanned operator in the stack)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
6. Now, we should repeat the steps 2 – 6 until the whole infix i.e. whole characters are
scanned.
7. Print output
8. Do the pop and output (print) until stack is not empty
Suggested Videos

https://www.youtube.com/watch?v=ndgYfRMIuX8

https://www.youtube.com/watch?v=A3ZUpyrnCbM

MIT Course
https://www.youtube.com/watch?v=CHhwJjR0mZA

You might also like