簡體   English   中英

2個單鏈表交集

[英]2 singly linked list intersection

我正在嘗試創建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)

您可以通過實現自定義__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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM