鏈表是常見的數(shù)據(jù)結(jié)構(gòu)之一,Python也提供了相應(yīng)的實(shí)現(xiàn)方法。當(dāng)我們需要判斷兩個(gè)鏈表是否相等時(shí),我們需要考慮鏈表中每個(gè)節(jié)點(diǎn)的值、節(jié)點(diǎn)的位置等多個(gè)因素。
class Node: def __init__(self, val=None, next=None): self.val = val self.next = next class LinkedList: def __init__(self): self.head = None #在鏈表結(jié)尾添加節(jié)點(diǎn) def add_node(self, val): node = Node(val) if not self.head: self.head = node else: current = self.head while current.next: current = current.next current.next = node #判斷兩個(gè)鏈表是否相等 def __eq__(self, other): if not isinstance(other, LinkedList): return False current1 = self.head current2 = other.head while current1 and current2: if current1.val != current2.val: return False current1 = current1.next current2 = current2.next return current1 is None and current2 is None a = LinkedList() a.add_node(1) a.add_node(2) b = LinkedList() b.add_node(1) b.add_node(2) c = LinkedList() c.add_node(1) c.add_node(3) print(a == b) #True print(a == c) #False
上述代碼定義了一個(gè)Node類和一個(gè)LinkedList類,其中LinkedList類包含了判斷兩個(gè)鏈表是否相等的方法。在main函數(shù)中,我們分別創(chuàng)建了鏈表a、b、c,其中a和b兩個(gè)鏈表相等,而a和c兩個(gè)鏈表不相等。可以看到,我們使用了雙指針的方法對(duì)兩個(gè)鏈表進(jìn)行遍歷,同時(shí)比較兩個(gè)鏈表中節(jié)點(diǎn)的值是否相等,最后返回判斷結(jié)果。