Data Structure
Data Structure
A B C D E F G H I
I= 0 1 2 3 4 5 6 7 8
B C
D E F
Fig: binary tree
Eg:
40 TOP
30
20
10
1
Eg:
C D TOP
TOP
PUSH C
B B
D A
A
Code:
def push(list,element):
list.append(element)
top=len(list)-1
2. POP OPERATION
To remove an element from the top of the stack
Eg: 15 12 10 5
TOP 15
12 TOP 12
10 10 TOP 10
5 5 5 TOP 5
3. PEEK
It inspect the element of list without removing it.
4. OVERFLOW
Attempt to insert new element in already full stack.
5. UNDERFLOW
Attempt to delete an element from already empty stack.
CODE IMPLIMENTATION
def empty(stack):
if stack==[ ]:
return True
else:
return False
def push(stack,element):
stack.append(element)
top=len(stack) -1
def pop(stack):
if empty(stack):
return “underflow”
else:
element=stack.pop()
if len(stack)= = 0:
top=None
else:
top=len(stack) -1
return element
def display(stack):
if empty(stack):
print(“stack is empty”)
else:
top=len(stack)
for i in range(top-1.-1.-1):
print(stack[i])
#main program----------------------------------------
stk = [ ]
top=None
a=”y”
while a= =”y” or a= = “Y”:
print(“1.PUSH”)
print(“1.POP”)
print(“1.DISPLAY”)
print(“1.EXIT”)
choice= input(“Enter Your Choice:\n”)
if choice= =1:
element=int(input(“Enter the Element”))
push(stk,element)
elif choice= = 2:
element=pop(stk)
if element= = “underflow”:
print(“stack is Empty”)
else:
print(“poped element is:\n”,element)
elif choice= =3:
print(“stack\n”)
show(stk)
elif choice= =4:
break
else:
print(“wrong input”)
OPERATION ON STACKS
There are 3 different operations
1. INFIX: operators are written in between the operands
Eg:
A*(B+C)/D
2. PREFIX: operators are written before the operands
Eg:
/*A+BCD
3. POSTFIX: operators are written in between the operands
Eg:
ABC+*D/
ALGORITHM TO CONVERT INFIX TO POSTFIX
1. Enclose the expression in parenthesis
2. Read next symbol of expression
3. If the symbol is operand then add it to output
4. If the symbol is “(“ then push in the stack
5. If the symbol is operator then:
i) Repeat while (priority of TOP >= priority of operator) pop
operator from stack and add operator to output
ii) Push operator into output
6. If symbol is “)”then
i) Repeat while (TOP (stack)!=’(‘ ) POP from stack and add
to operator.
ii) Remove the “(“.
Eg:
Evaluate the postfix expression and show the contents of the
stack after execution of each operation
( ( true && false)|| !(false || true))
scan Stack Output
( (
( ((
True (( True
&& ((&& True
False ((&& True false
) ( True false &&
|| (|| True false &&
! (||! True false &&
( (||!( True false &&
False (||!( True false && false
|| (||!(|| True false && false
True (||!(|| True false && false true
) (||! True false && false true||
) Empty stack True false && false true||!||
OUTPUT: 106