Combining linked lists iteratively

I am trying to combine two linked lists iteratively, but what I have now gives me the flip side of the result. Is there a way to combine the lists in the correct order without having to cancel if after creating the list of results?

class Link: 
    empty = ()

    def __init__(self, first, rest=empty):
        assert rest is Link.empty or isinstance(rest, Link)
        self.first = first
        self.rest = rest

    def __add__(self, lst):
        """ 
        >>>s = Link(1, Link(2))
        >>>s + Link(3,Link(4))
        Link(1,Link(2,Link(3,Link(4))))
        """
        result = Link.empty 
        while self is not Link.empty: 
            result = Link(self.first,result)
            self = self.rest 

        while lst is not Link.empty: 
            result = Link(lst.first, result)
            lst = lst.rest 
        return result 
+4
source share
2 answers

Avoid the change self, find the end of the first list and add a second list to it.

def __add__(self, lst):
    current = self

    while current.rest != self.empty:
        current = current.rest

    current.rest = lst

    return self

Or, if you prefer to return a new linked list:

def __add__(self, lst):
    new_list = Link(self.first)
    new_link = new_list

    current = self

    while current.rest != self.empty:
        new_link.rest = Link(current.first)
        new_link = new_link.rest

        current = current.rest

    current = lst

    while current != self.empty:
        new_link.rest = Link(current.first)
        new_link = new_link.rest

        current = current.rest

    return new_list

Note. This will make references to each value Link.first(and not independent copies).

0
source

, , , , , . , .

, , __add__ , self, lst, Link from self, lst , . :

def __add__(self, lst):
    result = Link(self.first)
    cur = result
    self = self.rest
    # Copy our list
    while self is not Link.empty:
        cur.rest = Link(self.first)
        cur = cur.rest
        self = self.rest
    # Copy and connect the Links in lst
    while lst is not Link.empty:
        cur.rest = Link(lst.first)
        cur = cur.rest
        lst = lst.rest
    return result

, , . , self Link(1,Link(2)).

    result = Link.empty 
    while self is not Link.empty: 
        result = Link(self.first,result)

result ?

  • Link(self.first,result)
  • Link(1, Link.empty)

        self = self.rest
    

self Link(2,())

        result = Link(self.first,result)

result ?

  • Link(self.first,result)
  • is Link(2, Link(1, Link.empty))

. ; .

0

All Articles