国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python判斷鏈表是否有環(huán)的實(shí)例代碼

2020-02-15 21:28:38
字體:
供稿:網(wǎng)友

先看下實(shí)例代碼:

class Node:  def __init__(self,value=None):    self.value = value    self.next = Noneclass LinkList:  def __init__(self,head = None):    self.head = head  def get_head_node(self):    """    獲取頭部節(jié)點(diǎn)    """    return self.head      def append(self,value) :    """    從尾部添加元素    """      node = Node(value = value)     cursor = self.head     if self.head is None:      self.head = node    else:        while cursor.next is not None:        cursor = cursor.next           cursor.next = node      if value==4:        node.next = self.head    def traverse_list(self):    head = self.get_head_node()    cursor = head    while cursor is not None:      print(cursor.value)      cursor = cursor.next    print("traverse_over")       def hasCycle(self, head):    """    :type head: ListNode    :rtype: bool    """    slow=fast=head    while slow and fast and fast.next:      slow = slow.next      fast = fast.next.next      if slow is fast:        return True    return False    def main():  l = LinkList()  l.append(1)  l.append(2)  l.append(3)  l.append(4)  head = l.get_head_node()  print(l.hasCycle(head))  #l.traverse_list()if __name__ == "__main__":  main()

知識(shí)點(diǎn)思考:

判斷一個(gè)單鏈表是否有環(huán),

可以用 set 存放每一個(gè) 節(jié)點(diǎn), 這樣每次 訪問后把節(jié)點(diǎn)丟到這個(gè)集合里面.

其實(shí) 可以遍歷這個(gè)單鏈表, 訪問過后,

如果這個(gè)節(jié)點(diǎn) 不在 set 里面, 把這個(gè)節(jié)點(diǎn)放入到 set 集合里面.

如果這個(gè)節(jié)點(diǎn)在 set 里面 , 說明曾經(jīng)訪問過, 所以這個(gè)鏈表有重新 走到了這個(gè)節(jié)點(diǎn), 因此一定有環(huán)

如果鏈表都走完了, 把所有的節(jié)點(diǎn)都放完了. 還是沒有重復(fù)的節(jié)點(diǎn), 那說明沒有環(huán).

以上就是本次介紹的全部相關(guān)知識(shí)點(diǎn)內(nèi)容,感謝大家的學(xué)習(xí)和對(duì)武林站長站的支持。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 教育| 赣州市| 哈密市| 界首市| 莱阳市| 永新县| 塔城市| 焉耆| 武定县| 金乡县| 侯马市| 万州区| 淮阳县| 会东县| 聊城市| 临夏县| 深水埗区| 县级市| 西平县| 青岛市| 江陵县| 于田县| 五河县| 蒲城县| 芜湖县| 革吉县| 句容市| 龙门县| 安康市| 和林格尔县| 西乌珠穆沁旗| 蕲春县| 锦屏县| 施甸县| 修文县| 襄垣县| 堆龙德庆县| 六枝特区| 罗源县| 宜川县| 阳泉市|