2015-01-09 182 views
0

我必须在堆栈中编写一个链表,这意味着我可以删除顶部的数字并从堆栈的顶端推送一个数字。不幸的是我的pop()方法FUNC不工作,我希望你能帮助我:从链表中删除一个节点(堆栈)

# ---------------init-------------- 
class node: 
    def __init__(self): 
     self.data = None # contains the data 
     self.next = None # contains the reference to the next node 


class linked_list: 
    def __init__(self): 
     self.cur_node = None 

# ---------------is_empty-------------- 
    def is_empty(self): 
    if self.cur_node == None: 
     print ("list is empty") 
    else: 
     print ("List = ") 
     ll.list_print() 

# ---------------is_full-------------- 

# ---------------push-------------- 

    def push(self, data): 
     new_node = node() # create a new node 
     new_node.data = data 
     new_node.next = self.cur_node # link the new node to the 'previous' node. 
     self.cur_node = new_node # set the current node to the new one. 

# ---------------pop-------------- 

    def pop(self): 
    print(node) 
    node = self.cur_node 
    while node: 
     if node.next == None: 
     node = None 
     break 
     else: 
     node=node.next 


# ---------------print-------------- 
    def list_print(self): 
     ... 


ll = linked_list() 

ll.is_empty() 
ll.push(1) 
ll.push(3) 
ll.push(2) 
ll.is_empty() 
ll.pop() 
ll.list_print() 

流行之前,电流输出()是

2 
3 
1 

pop()方法之后,它应该是

3 
1 
+2

我不知道python,但显然在你的'pop'中,你不会改变'self.cur_node',但只需按照堆栈的底部。刚刚使用'self.cur_node = self.cur_node.next'怎么样? – Codor 2015-01-09 20:12:36

+0

@Codor我的教授给了我一个写函数is_full()的练习。在我看来,不可能找到一个完整的链表,因为你总是可以创建一个“新节点”。我猜,这是他的错......你觉得呢? – WirJun 2015-01-09 20:20:46

+0

@Codor没错,就这么简单。 – augurar 2015-01-09 21:12:06

回答

1

您的代码当前迭代通过堆栈,不会修改任何内容。

考虑函数调用时堆栈的状态。在你的榜样,是这样的:

stack before pop

调用pop()后,你希望它是这样的:

stack after pop

因此,所有你需要做的是设置self.cur_nodeself.cur_node.next。您不必做任何事情来删除包含2的节点,Python将在不再引用它时自动执行此操作。

0

pop功能可能是这样可以帮到你

def pop(self, i): 
     '''(LinkedList, int) -> NoneType 
     Remove and return item at index. Raise IndexError if list is empty or 
     index is out of range.''' 

     if i < 0 or i >= self.num_elements: 
      raise IndexError("pop index out of range") 
     if i == 0: 
      result = self.front.key 
      self.front = self.front.next 
     else: 
      node = self.front 
      for j in range(i - 1): 
       node = node.next 
      result = node.next.key 
      node.next = node.next.next 
     self.num_elements -= 1 
     return result 
+0

与此func你可以搜索一个数字并删除它,但我必须删除最后一个元素,而不告诉编译器删除特殊位置上的特殊数字 – WirJun 2015-01-09 20:24:16

+1

def PopNode(self,index): prev =无 节点= self.head I = 0 而和(i <索引)(节点=无!): 先前=节点 节点= node.next I + = 1 如果一个先前==无: 自.head = node.next else: prev.next = node.next – Mobitips 2015-01-09 20:27:22

+0

为他完成OP的任务不会帮助他,再加上这个实现on与原始代码具有不同的签名,甚至不起作用(它期望节点具有'key'属性,而不是它们)。 – augurar 2015-01-09 21:04:12