简体   繁体   中英

Reversing order of numbers in linked list recursivly

I want to reverse the order of numbers in a linked list with recursion.

(1,(2,(3,( )))) ----> (3,(2,(1,( ))))

My linked lists, are nested tuples. First(xs) returns the first element, in the above example it would be either 1 or 3 on the right side. Rest(xs) returns all other elements, (2,(3,( ))) or (2,(1,( ) on the right side.

my code looks like this:

empty = ()
def reversed(xs):
    if xs == (first(xs), empty):
        return first(xs)
    else:
        return reversed(rest(xs)), first(xs)

but it yields in following output:

((3, 2), 1)

I guess, I'm pretty close, but I'm running out of ideas how to fix this.

Could anyone help me?

Thank you

There are different ways to do this. Right now, you are merely concatenating them to a new tuple, which does not create a properly formed linked list. Instead, you could append the former first to the reversed rest using a second function. Also, your base-case seems to be wrong, as you return just a single element instead of a linked list.

def reversed(xs):
    if xs == empty:
        return empty
    else:
        return append(reversed(rest(xs)), first(xs))

def append(xs, x):
    if xs == empty:
        return (x, empty)
    else:
        return first(xs), append(rest(xs), x)

>>> reversed((1, (2, (3, (4, empty)))))
(4, (3, (2, (1, ()))))

Note, however, that this has quadratic complexity O(n²) as you have to iterate the entire list (or partial list) to append the first node in each step of the reversed function. For a linear complexity O(n) version, you could add a second paramter to your reversed function (or create a second function to be called by the original function if you can't change the signature). This will build the reversed list in that second parameter and finally just return that list.

def reversed(xs, tail=empty):
    if xs == empty:
        return tail
    else:
        return reversed(rest(xs), (first(xs), tail))

Also, as noted in comments, there are better languages for defining recursive data structures than Python, and better ways to use lists in Python, but I'll assume that this is just for learning and not for practical use.

You can use simple recursion:

d = (1,(2,(3,())))
def reverse(_d, _c = ()):
  a, b = _d
  return (a, _c) if not b else reverse(b, (a, _c))

print(reverse(d))

Output:

(3, (2, (1, ())))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM