zoukankan      html  css  js  c++  java
  • 剑指offer-链表倒序输出,栈模拟队列

    链表倒序输出

    思路:

    用递归的方法,先输出后面的节点值在输出目前的节点值

    代码:

    class node:   #用类实现链表节点
        def __init__(self,data,next =None):
            self.data= data
            self.next=next
        data=0
        next=None
    def Printlink(head):
        while(head):
            if(head.next):
                Printlink(head.next)
            print(head.data)
            return
    head=None
    for i in range(6):
        head=node(i,head)
        p=head
    
    Printlink(p)
    

    两个栈模拟队列

    思路:

    入队的元素先压入stack1,出队时若stack2不为空,从stack2出栈,为空时将stack1的元素一个个压入stack2,再出栈。

    代码:

    
    class myq:
        def __init__(self):
            self.stack1=[]
            self.stack2=[]
        def push(self,v):
            self.stack1.append(v)
        def pop(self):
            if self.stack2:
                return self.stack2.pop()
            while self.stack1:
                self.stack2.append(self.stack1.pop())
            if self.stack2:
                return self.stack2.pop()
            else:
                return "ERROR"
    q=myq()
    q.push(1)
    q.push(2)
    print(q.pop())
    q.push(3)
    print(q.pop())
    q.push(4)
    print(q.pop())
    print(q.pop())
    print(q.pop())
    
    
  • 相关阅读:
    懒懒的~~
    BigDecimal,注解
    遇到的一点问题些
    npm一点点
    TortoiseSvn问题研究(一)
    关于maven-基本
    HttpServletRequest二三事
    学习迭代1需求分析
    FMDB简单使用
    计算机中的事务、回滚
  • 原文地址:https://www.cnblogs.com/void-lambda/p/12330179.html
Copyright © 2011-2022 走看看