使用栈实现一个文件中各行逆置的函数 --栈

版权声明:本文博主原创,转载请注明出处,感谢您的合作! https://blog.csdn.net/Thanlon/article/details/89314963
使用栈实现一个文件中各行逆置的函数:
# coding:utf8
class ReverseFile:
    def reverse_file(filename):
        S = ArrayStack()
        original = open(filename)
        for line in original:
            # It need to split by "\n" when original is  pushed
            S.push(line.rstrip('\n'))
        original.close()
        output = open(filename, 'w')
        while not S.is_empty():
            # "\n" need to be added again, when original is written
            output.write(S.pop() + '\n')
        output.close()


class ArrayStack:
    def __init__(self):
        # Create an empty stack
        self.__data = []

    def __len__(self):
        # Return the number of elements in the stack
        return len(self.__data)

    def is_empty(self):
        # Retutn True if the stack is empty
        return len(self.__data) == 0

    def push(self, e):
        # Add an element to the top of stack
        self.__data.append(e)

    def pop(self):
        # If element is empty ,it will raise Empty exception
        if self.is_empty():
            raise Empty('Stack is empty!')
        # Remove and return the element from the top of the stack
        return self.__data.pop()

    def top(self):
        # If element is empty ,it will raise Empty exception
        if self.is_empty():
            raise Empty('Stack is empty!')
        # Return the last item in the list
        return self.__data[-1]


class Empty(Exception):
    pass

猜你喜欢

转载自blog.csdn.net/Thanlon/article/details/89314963