2016-10-24 8 views
0

削除方法を修正してヘッドノードも削除できますか? リンクされたリストのヘッドノードを削除する

class LinkedListNode(): 
    def __init__(self, data=None, next_node=None): 
     self.data = data 
     self.next_node = next_node 


    def data(self): 
     return self.data 


    def next_node(self): 
     return self.next_node 


    def set_next_node(self, next_node): 
     self.next_node = next_node 

    def search(self, data): 
     index = 0 
     while self.next_node != None and self != None: 
      if self.data == data: 
       return index 
      else: 
       self = self.next_node 
       index += 1 
     return -1 

    def delete(self, data): 
     head = self 
     if self.data == data: 
      head = self.next_node 
     while self.next_node != None and self != None: 
      if self.next_node.data == data: 
       if self.next_node.next_node != None: 
        self.next_node = self.next_node.next_node 
       else: 
        self.next_node = None 
      else: 
       self = self.next_node 
     return head 


    def print(self): 
     while self.next_node != None: 
      print("%s: %s" % ("current node data is", self.data)) 
      self = self.next_node 
     if self.next_node == None and self != None: 
      print("%s: %s" % ("current node data is", self.data)) 

とテストファイル内

私が持っている:

from LinkedListNode import * 

head = LinkedListNode(3) 
node1 = LinkedListNode('cat') 
node2 = LinkedListNode('dog') 
node3 = LinkedListNode(4) 
head.set_next_node(node1) 
node1.set_next_node(node2) 
node2.set_next_node(node3) 

print(head.search('dog')) 
head.delete(3) 
head.delete(4) 
head.print() 

私が取得:すべての

2 
current node data is: 3 
current node data is: cat 
current node data is: dog 

Process finished with exit code 0 

答えて

0

まず、私はあなたが「自己」を再割り当てすることになっていないと信じています検索方法:

def search(self, data): 
    index = 0 
    while self.next_node != None and self != None: 
     if self.data == data: 
      return index 
     else: 
      self = self.next_node 
      index += 1 
    return -1 

単純な再帰的なバージョンと再試行:

def search(self, data): 
    if self.data == data: 
     return 0 
    elif self.next_node == None: 
     return -1 
    else: 
     idx = self.next_node.search(data) 
     if idx == -1: 
      return -1 
     else: 
      return 1 + idx 
関連する問題