2014-03-30 24 views
1

如何在不使用列表方法的情況下模擬堆棧的推送和彈出功能?使用列表結構但不列表方法的Python堆棧模擬

到目前爲止,我有這樣的事情,但我不知道是否這會工作:

stack = [] 

def Push(stack, element): 
    stack[len(stack)] = element 

def Pop(stack): 
    element = tos 
    stack[len(stack) - 1] = None 

    return element; 

將推動工作,動態地添加到列表中以這種方式,並會適當地len個更新?

對於pop,你將如何去從棧中「刪除」而不使用任何列表函數?

+1

'堆棧[LEN(棧)]'永遠如果'stack'是'list' –

回答

1

你可以使用類似這樣(警告:這是一個天真的實現 - 它不會對傳入的參數進行檢查)

class Stack(object): 
    def __init__(self): 
     self._stack = [] # Allocate an empty list 

    def push(self, ele): 
     self._stack += [ele] # Use list concatenation to emulate the `push` operation 

    def pop(self): 
     last = self._stack[-1:] # Return the last element of the list (also works for empty lists) 
     self._stack = self.stack[0:-1] # Copy the elements from the beginning of the list to the last element of the list 
     return last # return the last element 

    # All stacks should have the `size` function to determine how many elements are 
    # in the stack: 
    def size(self): 
     return len(self._stack) 

    # Occasionally you'll want to see the contents of the stack, so we have to 
    # implement the `__str__` magic method: 
    def __str__(self): 
     return '[%s]' % ','.join(map(str, self._stack)) 

注意:此方法不使用任何的list方法爲appendpop

例:

s = Stack() 

# fill the stack with values: 
for i in xrange(10): 
    s.push(i+1) 

print s # Outputs: [1,2,3,4,5,6,7,8,9,10] 

s.pop() 
s.pop() 

print s # Outputs: [1,2,3,4,5,6,7,8] 
+0

@ elykl33t失敗:我討厭迂腐,但它不一定是次級列表,而是*切片*。 ;)另外:你更受歡迎,也謝謝你! :) – jrd1

0

我想這個練習的目的是看作爲abstract data type的堆棧。你可以在不使用列表的情況下實現它們。如果你堅持使用列表,我不確定你的意思是「不使用列表方法」。

一個堆棧(作爲一個列表)是一個數據類型,它有兩個構造函數:(a)空棧和(b)將元素推入堆棧的結果。你可以在Python中想到這兩個不同的實現。例如,None可能是空棧,並且(x, s)可能是在s之上推動x的結果。我建議你在尋求更多幫助之前,嘗試自己做這樣的事情。

0

你可以預先分配的列表:

class Stack: 
    def __init__(self, max_items): 
     self.data = [0] * max_items 
     self.max_items = max_items 
     self.top = -1 

    def push(self, i): 
     self.top += 1 
     if self.top < self.max_items: 
      self.data[self.top] = i 
     else: 
      self.top -= 1 
      raise ValueError("stack is full") 

    def pop(self): 
     if self.top >= 0: 
      i = self.data[self.top] 
      self.top -= 1 
      return i 
     else: 
      raise ValueError("stack is empty") 

    def __len__(self): 
     return self.top + 1