Check if stack elements are pairwise consecutive | Function to check if elements are pairwise consecutive in stack ; Transfer elements of s to aux . ; Traverse aux and see if elements are pairwise consecutive or not . We also need to make sure that original content is retained . ; Fetch current top two elements of aux and check if they are consecutive . ; append the elements to original stack . ; Driver Code
def pairWiseConsecutive ( s ) : NEW_LINE INDENT aux = [ ] NEW_LINE while ( len ( s ) != 0 ) : NEW_LINE INDENT aux . append ( s [ - 1 ] ) NEW_LINE s . pop ( ) NEW_LINE DEDENT result = True NEW_LINE while ( len ( aux ) > 1 ) : NEW_LINE INDENT x = aux [ - 1 ] NEW_LINE aux . pop ( ) NEW_LINE y = aux [ - 1 ] NEW_LINE aux . pop ( ) NEW_LINE if ( abs ( x - y ) != 1 ) : NEW_LINE INDENT result = False NEW_LINE DEDENT s . append ( x ) NEW_LINE s . append ( y ) NEW_LINE DEDENT if ( len ( aux ) == 1 ) : NEW_LINE INDENT s . append ( aux [ - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ ] NEW_LINE s . append ( 4 ) NEW_LINE s . append ( 5 ) NEW_LINE s . append ( - 2 ) NEW_LINE s . append ( - 3 ) NEW_LINE s . append ( 11 ) NEW_LINE s . append ( 10 ) NEW_LINE s . append ( 5 ) NEW_LINE s . append ( 6 ) NEW_LINE s . append ( 20 ) NEW_LINE if ( pairWiseConsecutive ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT print ( " Stack ▁ content ▁ ( from ▁ top ) " , " after ▁ function ▁ call " ) NEW_LINE while ( len ( s ) != 0 ) : NEW_LINE INDENT print ( s [ - 1 ] , end = " ▁ " ) NEW_LINE s . pop ( ) NEW_LINE DEDENT DEDENT