2013-03-01 39 views
0

好了,我本來是要做到以下幾點:更改字符並反轉鏈接列表。 (蟒蛇)

使用類節點(經典建築)...

class No: 
     def __init__(self, valor, prox): 
     self.valor = valor 
     self.prox = prox 

做一個函數調用時會掉在2樓和3鏈接列表的字符,並將反向鏈接列表添加到原始列表的末尾。因此,如果我們做功能(列表),在lista = No(1,No(4,No(2,None)))(1> 4> 2)中,它將返回(1> 2> 4> 4> 2> 1 )。

問題在於我解決了這個問題,在常規列表中添加了術語並將它們與它們混合在一起。不過,後來我發現我應該只使用鏈表(即節點類我把上面的),現在我是一個有點無能......

代碼錯誤的解決方案:

class No: 
def __init__(self, valor, prox): 
    self.valor = valor 
    self.prox = prox 


def printLista(lista): 
    global lista1 
    lista1 = [] 
    while lista: 
     lista1.append(lista.valor) 
     lista = lista.prox 
    return lista1 


def printbackwards(lista): 
    global lista2 
    if lista == None: return 
    printbackwards(lista.prox) 
    lista2.append(lista.valor) 


def swapprint(lista): 
    global lista1, lista2 
    i = 0 
    lista2 = [] 
    printlist(lista) 
    printbackwards(lista) 
    for i in range(len(lista1)): 
     print lista1[i], lista2[i], 



lista = No(3, No(1, No(4, No(2, None)))) 
swapprint(lista) 

回答

0
class No: 
    def __init__(self,a,b): 
     self.val = a 
     self.next = b 
    def __str__(self): 
     return "%s->%s"%(self.val,self.next) 

def swapandReverse(lista): 
    n2 = lista.next #2nd element 
    n2.val,n2.next.val = n2.next.val,n2.val #swap 2,3 
    n = lista #root node 
    v = [] #hold our values 
    while n.next: 
     v.append(n.val) #add our value to list 
     n = n.next #move to next node 
    v.append(n.val) #append value of last node in the list 
    while len(v): #as long as we have values left in list 
     n.next = No(v.pop(-1),None) #set next to new node with our val 
     n = n.next 


lista = No(3,No(1,No(4,No(2,None)))) 
print lista 
swapandReverse(lista) 
print lista 

至少類似的東西

0

它不應該有必要使用全局變量爲您的鏈接列表操作。相反,您只需要以正確的方式遞歸,並將任何值返回給調用堆棧。我不知道我是否理解了你應該做的事情,因爲你的print函數實際上並沒有打印任何東西,但是如果你應該從舊的列表創建一個新列表,你可以做些什麼:

class Node(object): 
    def __init__(self, value, next=None): 
     self.value = value 
     self.next = next 

    def __str__(self): # borrowed from Joran Beasley's answer 
     return "%s->%s" % (self.value, self.next) 


def reverse_linked_list(lst, tail=None): 
    if lst is None: 
     return tail 
    else: 
     return reverse_linked_list(lst.next, Node(lst.value, tail)) 

def swap_23_linked_list(lst): 
    try: 
     second = lst.next 
     third = second.next 
    except AttributeError: # probably lst or lst.next is None! 
     raise ValueError("list is too sort to swap second and third values") 

    new_third = Node(second.value, third.next) # reuse all the nodes past third! 
    new_second = Node(third.value, new_third) 
    new_first = Node(lst.value, new_second) 

    return new_first 

實例:

>>> list_1 = Node(3, Node(1, Node(4, Node(2)))) 
>>> print(list_1) 
3->1->4->2->None 
>>> list_2 = reverse_linked_list(list_1) 
>>> print(list_2) 
2->4->1->3->None 
>>> list_3 = swap_23_linked_list(list_2) 
>>> print(list_3) 
2->1->4->3->None