兩個棧實現佇列 Python實現

2022-05-17 21:17:43 字數 2760 閱讀 5042

# coding=utf-8

max_length = 100

success = 1

fail = 0

error = -1

class queue(object):

stack_fir = none

stack_sec = none

queue_len = 0

def __init__(self):

self.stack_fir = stack()

self.stack_sec = stack()

self.queue_len = 0

# 佇列push方法

def push(self, item):

if self.queue_len == max_length:

return result(fail, none)

elif self.queue_len > max_length:

return result(error, none)

self.queue_len += 1

result = self.stack_fir.push(item)

if result.get_code() == success:

return result(success, none)

else:

return result(fail, none)

# 佇列pop方法

def pop(self):

if self.queue_len == 0:

return result(fail, none)

elif self.queue_len < 0:

return result(error, none)

self.queue_len -= 1

# 將裝有資料的棧拷貝到空棧中

while self.stack_fir.has_next():

pop_result = self.stack_fir.pop()

if pop_result.get_code() == success:

self.stack_sec.push(pop_result.get_value())

result = self.stack_sec.pop().get_value()

# 將裝有資料的棧拷貝到空棧中

while self.stack_sec.has_next():

pop_result = self.stack_sec.pop()

if pop_result.get_code() == success:

self.stack_fir.push(pop_result.get_value())

return result(success, result)

# 佇列是否有下乙個元素

def has_next(self):

return self.queue_len > 0

class stack(object):

stack_len = 0

item_list =

def __init__(self):

self.stack_len = 0

self.item_list =

# 棧push方法

def push(self, item):

if self.stack_len == max_length:

return result(fail, none)

elif self.stack_len > max_length:

return result(error, none)

self.stack_len += 1

return result(success, none)

# 棧pop方法

def pop(self):

if self.stack_len == 0:

return result(fail, none)

elif self.stack_len < 0:

return result(error, none)

self.stack_len -= 1

item = self.item_list[self.stack_len]

del self.item_list[self.stack_len]

return result(success, item)

# 棧是否有下乙個元素

def has_next(self):

return self.stack_len > 0

class result(object):

code = 0

value = none

def __init__(self, code, value):

self.code = code

self.value = value

def get_code(self):

return self.code

def get_value(self):

return self.value

if __name__ == '__main__':

queue = queue()

queue.push(1)

queue.push(2)

queue.push(5)

queue.push(4)

queue.push(3)

while queue.has_next():

print queue.pop().get_value()

兩個棧實現佇列 兩個佇列實現棧

1.兩個棧實現佇列 大致思路 入佇列時,將元素入棧s1,出佇列時,將s2中的元素出棧即可,如果s2為空,那麼將s1中 s1.size 1 個元素出棧,加入到s2中,然後將s1中最後乙個元素出棧,即完成了出佇列的操作 include using namespace std include includ...

兩個棧實現佇列,兩個佇列實現棧

include include include using namespace std 使用兩個棧實現佇列,實現了push,pop,front操作 其中棧s2是輔助棧,push直接在s1中插入 pop從s2中出棧,如果s2是空的,將s1倒進s2,然後再出棧,這樣減少了倒棧次數,比較高效。front就...

兩個棧實現佇列 兩個佇列實現棧

一 題目描述 用兩個棧來實現乙個佇列,完成佇列的push和pop操作。佇列中的元素為int型別。二 1 自己 基本思路 乙個棧用於壓縮,乙個專門用於彈出。因為棧是先進後出,所有的元素入棧再出棧,再入棧就可以將順序調整過來。但是沒有想到優化。class solution int pop int tem...