-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSort a stack using a temporary stack.py
More file actions
88 lines (70 loc) · 1.62 KB
/
Sort a stack using a temporary stack.py
File metadata and controls
88 lines (70 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Python program to sort a
# stack using auxiliary stack.
# This function return the sorted stack
def sortStack ( stack ):
tmpStack = createStack()
while(isEmpty(stack) == False):
# pop out the first element
tmp = top(stack)
pop(stack)
# while temporary stack is not
# empty and top of stack is
# greater than temp
while(isEmpty(tmpStack) == False and
int(top(tmpStack)) > int(tmp)):
# pop from temporary stack and
# push it to the input stack
push(stack,top(tmpStack))
pop(tmpStack)
# push temp in temporary of stack
push(tmpStack,tmp)
return tmpStack
# Below is a complete running
# program for testing above
# function.
# Function to create a stack.
# It initializes size of stack
# as 0
def createStack():
stack = []
return stack
# Function to check if
# the stack is empty
def isEmpty( stack ):
return len(stack) == 0
# Function to push an
# item to stack
def push( stack, item ):
stack.append( item )
# Function to get top
# item of stack
def top( stack ):
p = len(stack)
return stack[p-1]
# Function to pop an
# item from stack
def pop( stack ):
# If stack is empty
# then error
if(isEmpty( stack )):
print("Stack Underflow ")
exit(1)
return stack.pop()
# Function to print the stack
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end = ' ')
print()
# Driver Code
stack = createStack()
push( stack, str(34) )
push( stack, str(3) )
push( stack, str(31) )
push( stack, str(98) )
push( stack, str(92) )
push( stack, str(23) )
print("Sorted numbers are: ")
sortedst = sortStack ( stack )
prints(sortedst)
# This code is contributed by
# Prasad Kshirsagar