有没有一种方法可以对两个节点类型的类进行异或(其中一个可以为None)

时间:2020-05-21 08:49:14

标签: python algorithm data-structures

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.npx = None

class LinkedList:
    def __init__(self):
        self.head = None

    def XOR(self, a, b):
        return a ^ b


    def insert(self, data):

        new_node = Node(data)
        new_node.npx = self.head
        if self.head is not None:
            self.head.npx = self.XOR(new_node, self.head.npx)
            print(self.head.npx)
        self.head = new_node



    def printList(self):
        curr = self.head
        prev = None

        print("Following are the nodes of Linked List")
        while(curr):
            print(curr.data)
            next = self.XOR(prev, curr.npx)
            prev = curr
            curr = next



if __name__ == "__main__":
    llist = LinkedList()
    llist.insert(10)
    llist.insert(20)
    llist.insert(30)
    llist.insert(40)

    llist.printList()

这是我的错误代码 ^:“节点”和“ NoneType”的不受支持的操作数类型

我的任务是将单链接列表转换为xor链接列表 供参考: https://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-2/

这是链接 请帮助解决此问题,我已经做了最大的工作,但是在代码的异或方面却滞后了

1 个答案:

答案 0 :(得分:1)

我收到了^:'Node'和'NoneType'

的错误不受支持的操作数类型。

与您一样:

def XOR(self, a, b):
    return a ^ b

您必须使用支持^的参数,因为上述错误提示您将自己的类Node的对象用作a,因此应为Node提供适当的代码,称为magic method-在这种情况下是__xor__

__xor__(self, other) 使用^运算符实现按位异或。