-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f117e22
commit 4493b96
Showing
1 changed file
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
# Python program to print next greater element using stack | ||
|
||
# Stack Functions to be used by printNGE() | ||
|
||
|
||
def createStack(): | ||
stack = [] | ||
return stack | ||
|
||
|
||
def isEmpty(stack): | ||
return len(stack) == 0 | ||
|
||
|
||
def push(stack, x): | ||
stack.append(x) | ||
|
||
|
||
def pop(stack): | ||
if isEmpty(stack): | ||
print("Error : stack underflow") | ||
else: | ||
return stack.pop() | ||
|
||
|
||
'''prints element and NGE pair for all elements of | ||
arr[] ''' | ||
|
||
|
||
def printNGE(arr): | ||
s = createStack() | ||
element = 0 | ||
next = 0 | ||
|
||
# push the first element to stack | ||
push(s, arr[0]) | ||
|
||
# iterate for rest of the elements | ||
for i in range(1, len(arr), 1): | ||
next = arr[i] | ||
|
||
if isEmpty(s) == False: | ||
|
||
# if stack is not empty, then pop an element from stack | ||
element = pop(s) | ||
|
||
'''If the popped element is smaller than next, then | ||
a) print the pair | ||
b) keep popping while elements are smaller and | ||
stack is not empty ''' | ||
while element < next: | ||
print(str(element) + " -- " + str(next)) | ||
if isEmpty(s) == True: | ||
break | ||
element = pop(s) | ||
|
||
'''If element is greater than next, then push | ||
the element back ''' | ||
if element > next: | ||
push(s, element) | ||
|
||
'''push next to stack so that we can find | ||
next greater for it ''' | ||
push(s, next) | ||
|
||
'''After iterating over the loop, the remaining | ||
elements in stack do not have the next greater | ||
element, so print -1 for them ''' | ||
|
||
while isEmpty(s) == False: | ||
element = pop(s) | ||
next = -1 | ||
print(str(element) + " -- " + str(next)) | ||
|
||
|
||
# Driver code | ||
arr = [11, 13, 21, 3] | ||
printNGE(arr) | ||
|
||
|
||
|
||
|