更改字符和反转链接列表。 (蟒蛇)

时间:2013-03-01 00:49:04

标签: python list chained

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

使用Node类(经典构造)......

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

创建一个函数,调用时将交换链式列表的第2个和第3个字符,并将反向链接列表添加到原始列表的末尾。因此,如果我们执行功能(列表),则lista =否(1,否(4,否(2,无)))(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)

2 个答案:

答案 0 :(得分: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

至少是那样的

答案 1 :(得分: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