0

好吧,我应该做以下事情:

使用类节点(经典构造)...

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

创建一个函数,在调用时将交换链表的第二个和第三个字符,并在原始链表的末尾添加一个反向链表。因此,如果我们执行 function(list),则 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)
4

2 回答 2

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

至少是这样的

于 2013-03-01T01:06:59.903 回答
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
于 2013-03-01T01:30:00.920 回答