数据结构算法编程

1.打印一个链表,从尾到头打印链表

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        cur = listNode
        l=list() # l=[]
        while cur:
            l.append(cur.val)
            cur=cur.next
        return l[::-1]

2、用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型

思路:两个栈S1,S2,分别作为存储区和缓冲区

 入队时,将元素压入s1。

出队时,将s1的元素逐个“倒入”(弹出并压入)s2,将s2的顶元素弹出作为出队元素,之后再将s2剩下的元素逐个“倒回”s1。

见下面示意图:

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    def push(self, node):
        # write code here
        self.stack1.append(node)
        
    def pop(self):
        if self.stack2 ==[]:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()
        # return xx

猜你喜欢

转载自www.cnblogs.com/bethansy/p/9143767.html