经典算法题


面试题

  • 问题一:如何使用两个队列实现一个栈

    

import queue
 
 
class Stack(object):
 
    def __init__(self):
        self.master_queue = queue.Queue()
        self.minor_queue = queue.Queue()
 
    def push(self, value):
        """
        入栈
        :param value:
        :return:
        """
        self.master_queue.put(value)
 
    def pop(self):
        """
        出栈
        :return:
        """
        if self.master_queue.qsize() == 0:
            return None
 
        while True:
            if self.master_queue.qsize() == 1:
                value = self.master_queue.get()
                break
            self.minor_queue.put(self.master_queue.get())
 
        self.master_queue, self.minor_queue = self.minor_queue, self.master_queue
 
        return value
 
 
obj = Stack()
obj.push(1)
obj.push(2)
obj.push(3)
 
print(obj.pop())
print(obj.pop())
print(obj.pop())

 

 

 

 

  • 问题二:如何实现将单链表倒置

    

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

    def insert(self,item):
        node = Node(item)

        self.head = node.next
        if self.head == None:
            self.head =node
            return

        cur = self.head
        pre = None
        while cur:
            pre = cur
            cur = cur.next
        pre.next = node

    def travel(self):
        cur = self.head
        while cur:
            print(cur.item)
            cur = cur.next

    def remove(self,item):
        pre = None
        cur = self.head
        if cur.item == item :
            self.head = cur.next
            return
        while cur:
            pre = cur
            cur = cur.next
            if cur.item == item:
                pre.next = cur.next
                return


  '''链表倒置操作'''
    def reverse(self):
        cur = self.head
        pre = None
        next_node = cur.next

        while cur:
            cur.next = pre
            pre = cur
            cur = next_node
            if cur:
                next_node = cur.next
            self.head = pre
View Code

 

其实算法题在:题库 - 力扣 (LeetCode) 全球极客挚爱的技术成长平台 

 

posted @ 2020-04-25 12:30  y0um  阅读(159)  评论(0编辑  收藏  举报

新人优惠服务器