2016-04-08 66 views
-3

類_ListNode:如何在Python中複製鏈表?

class _ListNode: 
    def __init__(self, value, next_): 
     """ 
     ------------------------------------------------------- 
     Initializes a list node. 
     Use: node = _ListNode(value, _next) 
     ------------------------------------------------------- 
     Preconditions: 
      _value - data value for node (?) 
      _next - another list node (_ListNode) 
     Postconditions: 
      Initializes a list node that contains a copy of value 
      and a link to the next node in the list. 
     ------------------------------------------------------- 
     """ 
     self._value = copy.deepcopy(value) 
     self._next = next_ 
     return 

類List:

class List: 
    def __init__(self): 
     """ 
     ------------------------------------------------------- 
     Initializes an empty list. 
     Use: l = List() 
     ------------------------------------------------------- 
     Postconditions: 
      Initializes an empty list. 
     ------------------------------------------------------- 
     """ 
     self._front = None 
     self._count = 0 
     return 
    def copy(self): 
     """ 
     ------------------------------------------------------- 
     Duplicates the current list to a new list in the same order. 
     Use: new_list = l.copy() 
     ------------------------------------------------------- 
     Postconditions: 
      returns: 
      new_list - a copy of self (List) 
     ------------------------------------------------------- 

     """ 

的要求是寫複製功能。

但是,當我完成這個功能,因爲我的意見新列表只包含一個項目或無項目。

有沒有人能告訴我如何完成這個功能?

+1

請包括你寫的代碼。這裏沒有用於copy()函數的代碼。 –

回答

0

這應該工作:

import copy 
class _ListNode: 
    def __init__(self, value, next_): 
     self._value = copy.deepcopy(value) 
     self._next = next_ 
     return 
class List: 
    def __init__(self): 
     self._front = None 
     self._count = 0 
     return 
    def addToFront(self, value): 
     if self._front == None: 
      self._front = _ListNode(value, None) 
     else: 
      buffer = _ListNode(value, self._front) 
      self._front = buffer 

    def addToEnd(self, value): 
     current = self._front 
     if current: 
      while current._next != None: 
       current = current._next 
      current._next = _ListNode(value, None) 
     else: 
      self._front = _ListNode(value, None) 

    def __str__(self): 
     buffer = self._front 
     result = "" 
     while buffer._next != None: 
      result+= buffer._value + " > " 
      buffer = buffer._next 
     result+= buffer._value 
     return result 

    def copy(self): 
     result = List() 
     buffer = self._front 
     while buffer._next != None: 
      result.addToEnd(buffer._value) 
      buffer= buffer._next 
     result.addToEnd(buffer._value) 
     return result 

##test: 
x = List() 
x.addToFront("f") 
x.addToFront("e") 
x.addToFront("d") 
x.addToFront("c") 
x.addToFront("b") 
x.addToFront("a") 
print(x) 
print(x.copy())