Problems caused by python list inversion


-sharp
class Node(object):
    def __init__(self,data,nNext = None):
        self.data = data
        self.next = nNext
-sharp
class Chain(object):
    def __init__(self):
        self.head = None
        self.length = 0

    -sharp
    def append(self,dataOrNode):
        -sharpitemNode,Node
        if isinstance(dataOrNode,Node):
            item = dataOrNode
        else:
            item = Node(dataOrNode)
        -sharp
        if not self.head:
            self.head = item
            self.length += 1
        else:
            node = self.head
            -sharp
            while node.next:
                node = node.next
            -sharpitem
            node.next = item
            self.length += 1
    -sharp
    def delete(self,index):
        if index<0 or index>=self.length:
            return None

        current = self.head
        pre    = None
        temp_index = 0
        while current.next:
            if temp_index == index:
                if not pre:
                    self.head = current.next
                else:
                    pre.next = current.next
                self.length -= 1
                return
            pre = current
            current = current.next
            temp_index += 1
    -sharp
    def reverse(self,head):
        cur = head
        pre = None
        while cur is not None:
            -sharpprint(head)
            tmp = cur.next
            cur.next = pre
            pre = cur
            -sharpprint(pre.data)
            cur = tmp
        head = pre

problem: add 3 elements to the linked list, and then reverse

mychain = Chain()
mychain.append(1)
mychain.append(2)
mychain.append(3)
mychain.reverse(mychain.head)

node2 = mychain.head
while node2 is not None:
    print(node2.data)
    node2 = node2.next
1

pre reverses correctly, and the previous head re-assigns the current pre (the address pointed to by the previous head has become the address of the current pre). I think it"s quite right. In the past, mychain.head was 123, but now mychain.head is 321. It should be able to output 3-2-1 normally, but the result is only 1. I don"t understand
clipboard.png

.

Auxiliary Code:

head = {"a":1,"b":2}
def change(head):
    head["k"] = 2
change(head)
print(head)
:{"a": 1, "b": 2, "k": 2}headchangereverse

topic description

sources of topics and their own ideas

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

Apr.05,2021

because python is a value-passing operation, your operation in reverse does not change the head property of the class Chain. Try changing the last sentence to self.head = pre. But according to your code should be output 123, not just 1, this is a bit strange.


it is highly unrecommended to change loop variables in the body of a loop.

Menu