📌  相关文章
📜  在不使用额外空间的情况下克隆堆栈 |设置 2

📅  最后修改于: 2022-05-13 01:56:09.098000             🧑  作者: Mango

在不使用额外空间的情况下克隆堆栈 |设置 2

给定一个堆栈S ,任务是将给定堆栈S的内容复制到另一个堆栈T并保持相同的顺序。

例子:

反转基于堆栈的方法:有关反转基于堆栈的方法,请参阅本文的上一篇文章。

时间复杂度: O(N 2 )
辅助空间: O(1)

Linked List -Based Approach:有关基于链表的方法,请参阅本文上一篇文章。

时间复杂度: O(N)
辅助空间: O(1)

基于递归的方法:给定的问题也可以通过使用递归来解决。请按照以下步骤解决问题:

  • 定义一个递归函数,比如RecursiveCloneStack(stack S, stackDes)其中S是源堆栈,而Des是目标堆栈:
    • 定义一个基本情况,好像S.size()0然后从函数返回。
    • 将源堆栈的顶部元素存储在变量中,例如val ,然后删除堆栈S的顶部元素。
    • 现在使用更新的源堆栈SRecursiveCloneStack(S, Des)调用递归函数。
    • 完成上述步骤后,将val压入Des堆栈。
  • 初始化一个堆栈,比如Des来存储目标堆栈。
  • 现在调用函数RecursiveCloneStack(S, Des)将源堆栈的元素复制到目标堆栈。
  • 完成上述步骤后,打印堆栈Des的元素作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Auxiliary function to copy elements
// of source stack to destination stack
void RecursiveCloneStack(stack& S,
                         stack& Des)
{
    // Base case for Recursion
    if (S.size() == 0)
        return;
 
    // Stores the top element of the
    // source stack
    int val = S.top();
 
    // Removes the top element of the
    // source stack
    S.pop();
 
    // Recursive call to the function
    // with remaining stack
    RecursiveCloneStack(S, Des);
 
    // Push the top element of the source
    // stack into the Destination stack
    Des.push(val);
}
 
// Function to copy the elements of the
// source stack to destination stack
void cloneStack(stack& S)
{
    // Stores the destination stack
    stack Des;
 
    // Recursive function call to copy
    // the source stack to the
    // destination stack
    RecursiveCloneStack(S, Des);
 
    cout << "Destination:- ";
    int f = 0;
 
    // Iterate until stack Des is
    // non-empty
    while (!Des.empty()) {
 
        if (f == 0) {
            cout << Des.top();
            f = 1;
        }
 
        else
            cout << "              "
                 << Des.top();
        Des.pop();
 
        cout << '\n';
    }
}
 
// Driver Code
int main()
{
    stack S;
    S.push(1);
    S.push(2);
    S.push(3);
    S.push(4);
    S.push(5);
    cloneStack(S);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class Main
{
    static Stack S = new Stack();
    static Stack Des = new Stack(); // Stores the destination stack
      
    // Auxiliary function to copy elements
    // of source stack to destination stack
    static void RecursiveCloneStack()
    {
       
        // Base case for Recursion
        if (S.size() == 0)
            return;
        
        // Stores the top element of the
        // source stack
        int val = S.peek();
        
        // Removes the top element of the
        // source stack
        S.pop();
        
        // Recursive call to the function
        // with remaining stack
        RecursiveCloneStack();
        
        // Push the top element of the source
        // stack into the Destination stack
        Des.push(val);
    }
      
    // Function to copy the elements of the
    // source stack to destination stack
    static void cloneStack()
    {
        // Recursive function call to copy
        // the source stack to the
        // destination stack
        RecursiveCloneStack();
        
        System.out.print("Destination:- ");
        int f = 0;
        
        // Iterate until stack Des is
        // non-empty
        while (Des.size() > 0) {
        
            if (f == 0) {
                System.out.print(Des.peek());
                f = 1;
            }
        
            else
                System.out.print("              " + Des.peek());
            Des.pop();
        
            System.out.println();
        }
    }
     
  // Driver code
    public static void main(String[] args) {
        S.push(1);
        S.push(2);
        S.push(3);
        S.push(4);
        S.push(5);
        cloneStack();
    }
}
 
// This code is contributed by mukesh07.


Python3
# Python3 program for the above approach
 
S = []
Des = [] # Stores the destination stack
   
# Auxiliary function to copy elements
# of source stack to destination stack
def RecursiveCloneStack():
    
    # Base case for Recursion
    if (len(S) == 0):
        return
     
    # Stores the top element of the
    # source stack
    val = S[-1]
     
    # Removes the top element of the
    # source stack
    S.pop()
     
    # Recursive call to the function
    # with remaining stack
    RecursiveCloneStack()
     
    # Push the top element of the source
    # stack into the Destination stack
    Des.append(val)
   
# Function to copy the elements of the
# source stack to destination stack
def cloneStack():
    # Recursive function call to copy
    # the source stack to the
    # destination stack
    RecursiveCloneStack()
     
    print("Destination:- ", end = "")
    f = 0
     
    # Iterate until stack Des is
    # non-empty
    while len(Des) > 0:
        if (f == 0):
            print(Des[-1], end = "")
            f = 1
     
        else:
            print("             ", Des[-1], end = "")
        Des.pop()
     
        print()
 
S.append(1)
S.append(2)
S.append(3)
S.append(4)
S.append(5)
cloneStack()
 
# This code is contributed by decode2207.


C#
// C# program for the above approach
using System;
using System.Collections;
class GFG {
     
    static Stack S = new Stack();
    static Stack Des = new Stack(); // Stores the destination stack
     
    // Auxiliary function to copy elements
    // of source stack to destination stack
    static void RecursiveCloneStack()
    {
        // Base case for Recursion
        if (S.Count == 0)
            return;
       
        // Stores the top element of the
        // source stack
        int val = (int)S.Peek();
       
        // Removes the top element of the
        // source stack
        S.Pop();
       
        // Recursive call to the function
        // with remaining stack
        RecursiveCloneStack();
       
        // Push the top element of the source
        // stack into the Destination stack
        Des.Push(val);
    }
     
    // Function to copy the elements of the
    // source stack to destination stack
    static void cloneStack()
    {
        // Recursive function call to copy
        // the source stack to the
        // destination stack
        RecursiveCloneStack();
       
        Console.Write("Destination:- ");
        int f = 0;
       
        // Iterate until stack Des is
        // non-empty
        while (Des.Count > 0) {
       
            if (f == 0) {
                Console.Write(Des.Peek());
                f = 1;
            }
       
            else
                Console.Write("              " + Des.Peek());
            Des.Pop();
       
            Console.WriteLine();
        }
    }
 
  static void Main() {
    S.Push(1);
    S.Push(2);
    S.Push(3);
    S.Push(4);
    S.Push(5);
    cloneStack();
  }
}
 
// This code is contributed by divyesh072019.


Javascript


输出:
Destination:- 5
              4
              3
              2
              1

时间复杂度: O(N)
辅助空间: O(1)