Search code examples
pythonlistchained

Changing characters and reversing chained lists. (python)


Well, I was supposed to do the following:

Using the class Node (classic construction)...

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

to make a function that when called will swap the 2nd and 3rd characters of a chained list and add a backward chained list to the end of the original one. So if we do function(list), being lista = No(1, No(4, No(2, None))) (1>4>2) it will return (1>2>4>4>2>1).

The problem with that is that I solved the problem by adding the terms to regular lists and messing with them there. However, then I found out I was supposed to only use chained lists (that node class I put above) and now I'm a bit clueless...

Code for the wrong solution:

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)

Solution

  • 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
    

    at least something like that