📌  相关文章
📜  在没有额外空间的情况下克隆堆栈

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

在没有额外空间的情况下克隆堆栈

给定一个源堆栈,将源堆栈的内容复制到目标堆栈,保持相同的顺序,而不使用额外的空间。
例子:

Input : Source:- |3|
                 |2|
                 |1|

Output : Destination:- |3|
                       |2|
                       |1|

Input : Source:- |a|
                 |b|
                 |c|

Output : Destination:- |a|
                       |b|
                       |c|

做法:为了在不占用额外空间的情况下解决这个问题,我们先将源栈反转,然后将源栈的顶部元素一个一个弹出入目标栈。我们按照以下步骤反转源堆栈:

  1. 将变量计数初始化为 0。
  2. 从源堆栈中弹出顶部元素并将其存储在变量topVal中。
  3. 现在从源堆栈中弹出元素并将它们推入目标堆栈,直到源堆栈的长度等于count
  4. topVal推入源堆栈,然后将目标堆栈中的所有元素弹出并推入源堆栈。
  5. 增加count的值。
  6. 如果计数不等于源堆栈的长度 - 1,则从步骤 2 开始重复该过程。

下面是上述方法的实现:

Python3
# Python3 program to copy the contents from source stack
# into destination stack without using extra space
 
# Define a class for Stack
class Stack(object):
     
    def __init__(self):
        self.stack = []
         
    def push(self, value):
        self.stack.append(value)
         
    def pop(self):
        return self.stack.pop()
         
    def length(self):
        return len(self.stack)
         
    def display(self):
        for i in range(len(self.stack)-1, -1, -1):
            print(self.stack[i])
             
        print()
         
source = Stack()     # Source Stack
dest = Stack()         # Destination Stack
 
source.push(1)
source.push(2)
source.push(3)
 
print("Source Stack:")
source.display()
 
count = 0
 
# Reverse the order of the values in source stack
while count != source.length() - 1:
     
    topVal = source.pop()
    while count != source.length():
        dest.push(source.pop())
         
    source.push(topVal)
    while dest.length() != 0:
        source.push(dest.pop())
         
    count += 1
 
# Pop the values from source and push into destination stack
while source.length() != 0:
    dest.push(source.pop())
     
print("Destination Stack:")
dest.display()


Python3
# Python3 program to copy the contents from source stack
# into destination stack without using extra space
# in linear time using Linked List
 
class StackNode(object):
     
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Class for Stack to represent it as Linked list
class Stack(object):
     
    def __init__(self):
        self.top = None
         
    def push(self, value):
         
        newVal = StackNode(value)
         
        if self.top == None:
            self.top = newVal
         
        else:
            newVal.next = self.top
            self.top = newVal
     
    def pop(self):
         
        val = self.top.data
        self.top = self.top.next
        return val
         
    def display(self):
         
        current = self.top
        while current != None:
            print(current.data)
            current = current.next
             
        print()
         
    def reverse(self):
         
        current, temp, prev = self.top, None, None
         
        while current != None:
            temp = current.next
            current.next = prev
            prev = current
            current = temp
             
        self.top = prev
     
    def isEmpty(self):
        return self.top == None
         
source = Stack()        # Source Stack
dest = Stack()          # Destination Stack
 
source.push(1)
source.push(2)
source.push(3)
 
print("Source Stack:")
source.display()
 
source.reverse()
 
# Pop the values from source and push into destination stack
while source.isEmpty() != True:
    dest.push(source.pop())
     
print("Destination Stack:")
dest.display()


输出:

Source Stack:
3
2
1

Destination Stack:
3
2
1

时间复杂度: O(n^2)
有效方法:更好的方法是将堆栈表示为链表。反转源栈的方式与我们反转链表的方式相同,将源栈的顶部元素一个接一个地弹出,然后其压入目标栈。
下面是上述方法的实现:

Python3

# Python3 program to copy the contents from source stack
# into destination stack without using extra space
# in linear time using Linked List
 
class StackNode(object):
     
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Class for Stack to represent it as Linked list
class Stack(object):
     
    def __init__(self):
        self.top = None
         
    def push(self, value):
         
        newVal = StackNode(value)
         
        if self.top == None:
            self.top = newVal
         
        else:
            newVal.next = self.top
            self.top = newVal
     
    def pop(self):
         
        val = self.top.data
        self.top = self.top.next
        return val
         
    def display(self):
         
        current = self.top
        while current != None:
            print(current.data)
            current = current.next
             
        print()
         
    def reverse(self):
         
        current, temp, prev = self.top, None, None
         
        while current != None:
            temp = current.next
            current.next = prev
            prev = current
            current = temp
             
        self.top = prev
     
    def isEmpty(self):
        return self.top == None
         
source = Stack()        # Source Stack
dest = Stack()          # Destination Stack
 
source.push(1)
source.push(2)
source.push(3)
 
print("Source Stack:")
source.display()
 
source.reverse()
 
# Pop the values from source and push into destination stack
while source.isEmpty() != True:
    dest.push(source.pop())
     
print("Destination Stack:")
dest.display()

输出:

Source Stack:
3
2
1

Destination Stack:
3
2
1

时间复杂度: O(n)