Печатать элементы стопки снизу вверх

Опубликовано: 14 Января, 2022

Учитывая стек s, задача состоит в том, чтобы распечатать элементы стека снизу вверх, чтобы элементы все еще присутствовали в стеке без изменения их порядка в стеке.

Примеры:

 Вход : 
       
       
| 4 |
| 3 |
| 2 |
| 1 |
| ________ |

Выход: 1 2 3 4
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Подход 1 (рекурсия): идея состоит в том, чтобы вытолкнуть элемент стека и вызвать рекурсивную функцию PrintStack. Как только стек станет пустым, начните печатать элемент, который был вытянут последним, и последний элемент, который был вытянут, был самым нижним элементом. Таким образом, элементы будут печататься снизу вверх. Теперь верните напечатанный элемент, это сохранит порядок элементов в стеке.

Below is the implementation of the above approach:

C++

// C++ program to print the elements of a
// stack from bottom to top
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to print stack elements
// from bottom to top without changing
// their order
void PrintStack(stack<int> s)
{
    // If stack is empty then return
    if (s.empty())
        return;
     
 
    int x = s.top();
 
    // Pop the top element of the stack
    s.pop();
 
    // Recursively call the function PrintStack
    PrintStack(s);
 
    // Print the stack element starting
    // from the bottom
    cout << x << " ";
 
    // Push the same element onto the stack
    // to preserve the order
    s.push(x);
}
 
// Driver code
int main()
{
    // Stack s
    stack<int> s;
 
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
 
    PrintStack(s);
 
    return 0;
}

Java

// Java program to print the elements of a
// stack from bottom to top
import java.util.*;
 
class GfG
{
 
// Recursive function to print stack elements
// from bottom to top without changing
// their order
static void PrintStack(Stack<Integer> s)
{
    // If stack is empty then return
    if (s.isEmpty())
        return;
     
    int x = s.peek();
 
    // Pop the top element of the stack
    s.pop();
 
    // Recursively call the function PrintStack
    PrintStack(s);
 
    // Print the stack element starting
    // from the bottom
    System.out.print(x + " ");
 
    // Push the same element onto the stack
    // to preserve the order
    s.push(x);
}
 
// Driver code
public static void main(String[] args)
{
    // Stack s
    Stack<Integer> s = new Stack<Integer> ();
 
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
 
    PrintStack(s);
}
}
 
// This code is contributed by Prerna Saini.

Python3

# Python3 program to print the elements of a
# stack from bottom to top
 
# Stack class with all functionality of a stack
import sys
class Stack:
    def __init__(self):
        self.s = []
 
    def push(self, data):
        self.s.append(data)
     
    def pop(self):
        return self.s.pop()
 
    def peek(self):
        return self.s[-1]
    def count(self):
        return len(self.s)
 
# Recursive function to print stack elements
# from bottom to top without changing
# their order
def printStack(s):
     
    # if stack is empty then simply return
    if s.count() == 0:
        return
    x = s.peek()
 
    # pop top most element of the stack
    s.pop()
     
    # recursively call the function printStack
    printStack(s)
     
    # Print the stack element starting
    # from the bottom
    print("{} ".format(x), end = "")
     
    # Push the same element onto the stack
    # to preserve the order
    s.push(x)
 
# Driver code
if __name__=="__main__":
    s=Stack()
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
 
    printStack(s)
 
# This code is contributed by Vikas Kumar

C#

// C# program to print the elements of a
// stack from bottom to top
using System;
using System.Collections.Generic;
 
class GfG
{
 
// Recursive function to print stack elements
// from bottom to top without changing
// their order
static void PrintStack(Stack<int> s)
{
    // If stack is empty then return
    if (s.Count == 0)
        return;
     
    int x = s.Peek();
 
    // Pop the top element of the stack
    s.Pop();
 
    // Recursively call the function PrintStack
    PrintStack(s);
 
    // Print the stack element starting
    // from the bottom
    Console.Write(x + " ");
 
    // Push the same element onto the stack
    // to preserve the order
    s.Push(x);
}
 
// Driver code
public static void Main()
{
    // Stack s
    Stack<int> s = new Stack<int> ();
 
    s.Push(1);
    s.Push(2);
    s.Push(3);
    s.Push(4);
 
    PrintStack(s);
}
}
 
/* This code contributed by PrinciRaj1992 */
Output: 

1 2 3 4