2单链表交集

2024-05-15 17:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建两个单链表,并找到它们之间的交集。我得到了一些错误,比如NameError:obj没有为LinkedList行定义,需要一个有效的解决方案。我该怎么做?我做错什么了?我还差一点吗?生命的意义是什么?这是python语言。在

class IntersectSolution:
    def intersect(sll_a, sll_b):
        b_x_node = sll_b
        while sll_b and not sll_a.search(sll_b.get_data()):
            sll_b.get_next()
            b_x_node = sll_b
        if b_x_node == None:
            print("No intersections between nodes.")
        print("Intersection node is: {}".format(b_x_node))

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

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

    def set_next(self, new_node):
        self.next_node = new_node

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

    def insert(self, data):
        new_node = Node(data)
        new_node.set_next(self.head)
        self.head = new_node

    def size(self):
        current = self.head
        count = 0
        while current:
            count += 1
            current = current.get_next
        return count

    def search(self, data):
        current = self.head
        found = False
        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                current = current.get_next()
        if current is None:
            raise ValueError("Data not in list")
        return current

    def delete(self, data):
        current = self.head
        previous = None
        found = False
        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                previous = current
                current = current.get_next()
        if current is None:
            raise ValueError("Data not in list")
        if previous is None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

a = LinkedList(Node)
b = LinkedList(Node)
for i in range(1, 15, 2):
    a.insert(i)
for j in range(23, 8, -3):
    b.insert(j)

ISoln = IntersectSolution
ISoln.intersect(a,b)

Tags: selfnonenodenewdatagetifis
1条回答
网友
1楼 · 发布于 2024-05-15 17:29:31

通过实现自定义的__add__方法,然后在两个原始列表中的串联结果中查找值,可以将两个链接列表串联起来:

class LinkedList:
   def __init__(self, _val=None):
     self.val = _val
     self._next = None
   def insert(self, _val):
     if self.val is None:
       self.val = _val
     else:
       getattr(self._next, 'insert', lambda x:setattr(self, '_next', LinkedList(x)))(_val)
   def __iter__(self): #iterate over all values in list
      yield self.val
      yield from [[], self._next][bool(self._next)]
   def __add__(self, _list): #concatenate two linkedlists
      _l = self.__class__()
      for i in _list:
         _l.insert(i)
      for i in self:
         _l.insert(i)
      return _l
   def __contains__(self, _val): #check if a value exists in the list
      if self.val is None:
        return False
      return True if self.val == _val else getattr(self._next, '__contains__', lambda _:False)(_val)
   @classmethod
   def intersection(cls, _a, _b):
     _result = cls()
     for i in (_a+_b):
       if i in _a and i in _b and i not in _result:
         _result.insert(i)
     return _result

^{pr2}$

输出:

[6, 7, 8, 9]

相关问题 更多 >