2 односвязных пересечения списка

1

Я пытаюсь создать 2 одиночных связанных списков и найти пересечение между ними. Я получаю ошибки, такие как 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)
  • 0
    также получаю эту ошибку в моей инициализации цикла for a и b - insert () отсутствует 1 обязательный позиционный аргумент: 'data' ... я удалил параметры obj; поэтому удалив параметр Node в LinkedList, он продвинулся дальше.
  • 0
    получение этой ошибки при вставке внутри класса LinkedList - AttributeError: объект типа «LinkedList» не имеет атрибута «head» ... Разве init_ не должен покрывать эту проблему и давать ему этот атрибут?
Теги:
linked-list
singly-linked-list

1 ответ

0
Лучший ответ

Вы можете объединить оба связанных списка, __add__ собственный метод __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]
  • 0
    Работал на меня, не волнуйтесь.
  • 0
    @ RyanWolfe9013 Рад помочь!
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню