剑指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())

posted @ 2020-02-19 10:43  four_z  阅读(135)  评论(0)    收藏  举报