2个单链表交集

时间:2018-07-31 01:19:38

标签: python linked-list singly-linked-list

我正在尝试创建2个单链表并找到它们之间的交集。我遇到诸如NameError的错误:未为LinkedList行定义obj,并且想要一个可行的解决方案。我该如何工作?我究竟做错了什么?我什至靠近吗?什么是生命的意义?这是在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)

1 个答案:

答案 0 :(得分:0)

您可以通过实现自定义__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

l = LinkedList()
for i in range(10):
  l.insert(i)

l1 = LinkedList() 
for i in range(6, 14):
  l1.insert(i)

_intersection = LinkedList.intersection(l, l1)
print([i for i in _intersection])

输出:

[6, 7, 8, 9]