【发布时间】:2011-06-18 16:28:31
【问题描述】:
是python代码..是否使用链表实现....这样效率高............
data = [] # data storage for stacks represented as linked lists
stack = [-1, -1, -1] # pointers to each of three stacks (-1 is the "null" pointer)
free = -1 # pointer to list of free stack nodes to be reused
def allocate(value):
''' allocate a new node and return a pointer to it '''
global free
global data
if free == -1:
# free list is empty, need to expand data list
data += [value,-1]
return len(data)-2
else:
# pop a node off the free list and reuse it
temp = free
free = data[temp+1]
data[temp] = value
data[temp+1] = -1
return temp
def release(ptr):
''' put node on the free list '''
global free
temp = free
free = ptr
data[free+1] = temp
def push(n, value):
''' push value onto stack n '''
global free
global data
temp = stack[n]
stack[n] = allocate(value)
data[stack[n]+1] = temp
def pop(n):
''' pop a value off of stack n '''
value = data[stack[n]]
temp = stack[n]
stack[n] = data[stack[n]+1]
release(temp)
return value
def list(ptr):
''' list contents of a stack '''
while ptr != -1:
print data[ptr],
ptr = data[ptr+1]
print
def list_all():
''' list contents of all the stacks and the free list '''
print stack,free,data
for i in range(3):
print i,":",
list(stack[i])
print "free:",
list(free)
push(0,"hello")
push(1,"foo")
push(0,"goodbye")
push(1,"bar")
list_all()
pop(0)
pop(0)
push(2,"abc")
list_all()
pop(1)
pop(2)
pop(1)
list_all()
r 除了这个之外还有什么方法可以有效地做到这一点??以这种方式在 c /c++ 中实现会很有效???
【问题讨论】:
-
天啊,这些年来我都不知道 C 和 C++ 是什么!!!
-
问题被标记为 C 和 C++,但代码看起来像 Python(当然,它看起来像一些 C/C++ 人会编写的 Python 代码,但仍然如此)。
-
@Armen Tsirunyan 它不是 c/c++ 代码。这是一个python代码......
-
那你为什么把它标记为C和C++?
-
@learn 哦,真的吗?那是一种解脱。有那么一瞬间,我以为是“C/C++”代码……我可以谦虚地问一下,为什么你的问题被标记为 C 和 C++ 吗? ;)
标签: python