原题
实现一个双端队列
样例
push_front(1)
push_back(2)
pop_back() // return 2
pop_back() // return 1
push_back(3)
push_back(4)
pop_front() // return 3
pop_front() // return 4
解题思路
- 自己构建一个双向链表
- 需要注意从前面pop出最后一个元素和从后面pop出最后一个元素的情况
完整代码
class Node():
def __init__(self, _val):
self.next = self.prev = None
self.val = _val
class Dequeue(object):
def __init__(self):
# do some intialize if necessary
self.first, self.last = None, None
# @param {int} item an integer
# @return nothing
def push_front(self, item):
# Write yout code here
if self.first is None:
self.first = Node(item)
self.last = self.first
else:
tmp = Node(item)
self.first.prev = tmp
tmp.next = self.first
self.first = tmp
# @param {int} item an integer
# @return nothing
def push_back(self, item):
# Write yout code here
if self.last is None:
self.first = Node(item)
self.last = self.first
else:
tmp = Node(item)
self.last.next = tmp
tmp.prev = self.last
self.last = tmp
# @return an integer
def pop_front(self):
# Write your code here
if self.first is not None:
item = self.first.val
self.first = self.first.next
if self.first is not None:
self.first.prev = None
else:
self.last = None
return item
return -12
# @return an integer
def pop_back(self):
# Write your code here
if self.last is not None:
item = self.last.val
self.last = self.last.prev
if self.last is not None:
self.last.next = None
else:
self.first = None
return item
return -12