将操作存储在堆栈中以撤消'目的

时间:2017-09-19 00:35:42

标签: python class

因为stack允许push或pop,所以只需简单地弹出用户的最新动作就可以重做动作。我有一个堆栈类:

class Node:
    def __init__(self,item,the_next = None):
        self.item = item
        self.next = the_next

    def __str__(self):
        return str(self.item)

class LinkedStack:
    def __init__(self):
        self.top = None
        self.count = 0

    def __len__(self):
        return self.count

    def is_empty(self):
        return self.count == 0

    def isFull(self):
        return False

    def reset(self):
        self.top = None
        self.count = 0

    def __str__(self):
        current = self.top
        ans = ""
        while not (current is None):
            ans += str(current)
            ans += '\n'
            current = current.next
        return ans

    def _get_node(self,index):
        if 0<= index< len(self):
            current = self.top
            while index>0:
               current = current.next
               index -=1
            return current

    def pop(self):
        if self.is_empty():
            raise StopIteration("Stack is empty")
        output = self.top.item
        self.top = self.top.next
        self.count -=1
        return output

    def push(self,item):
        newNode = Node(item)
        newNode.next = self.top
        self.top = newNode
        self.count +=1

if __name__ == "__main__":
    L = LinkedStack()

在另一个文件中,我从上面导入堆栈并尝试实现撤消操作。

from Stack import LinkedStack
class Editor:
    def __init__(self):
        self.count = 0
        self._list = LinkedList()
        self._stack = LinkedStack()

def command(self,userCommand):
    userCommand = userCommand.split(' ')
    try:
        if userCommand[0] == 'insert':
            position = int(userCommand[1])
            if len(userCommand) ==1:
                raise Exception('no num is given')
            textInput = input("Enter your text:")
            self._stack.push(self.insertText(position,textInput)) #I'm thinking of adding the action into the stack by pushing it.
            print(self._list)
            pass
    except Exception:
        print('?')

    if userCommand[0] == 'undo':   #here if they choose to undo, by right i just pop the last action from the stack
        self._stack.pop()

if __name__ == '__main__':
    myCommand = Editor()
    while True:
        command = input('Enter an option:')
        if command.lower() == 'quit':
           break
        else:
            myCommand.command(command)

因为我只是撤消动作,我想把命令动作添加到堆栈中。如果你看一下上面的插入命令,我添加了一个注释,我正确地做了吗?因为我的想法已经不多了。

顺便说一句,insertText是一个有效的功能,我不打算将它粘贴在这里,因为它变得冗长。 LinkedList()只是我从另一个文件导入的链表类。

&#39;撤消&#39;似乎没有恢复国家。例如,如果我的LinkedList()包含:

1
2
3
4
None

如果我使用插入函数插入另一个数字,7在索引1

1
7
2
3
4
None

如果我撤消动作,我应该有:

1
2
3
4
None

0 个答案:

没有答案