鏈表筆試題

  1. 反轉鏈表
# 節點
class Node(object):
    def __init__(self, elem):
        self.elem = elem
        self.next = None

# 鏈表
class SingleList(object):
    def __init__(self, head):
        self.head = head

    #  反轉鏈表
    def reverseSingleList(self, head):
        if head == None or head.next == None:
            return
        l, m, r = head, head.next, head.next.next
        while r:
            m.next = l
            l = m
            m = r
            r = r.next
        m.next = l
        return m

if __name__ == '__main__':
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    print("原鏈表:")
    print(head.elem)
    print(head.next.elem)
    print(head.next.next.elem)
    print(head.next.next.next.elem)
    singleList = SingleList(head)
    m = singleList.reverseSingleList(singleList.head)
    print("反轉後鏈表:")
    print(m.elem)
    print(m.next.elem)
    print(m.next.next.elem)
    print(m.next.next.next.elem)
  1. 判斷鏈表是否有環(快慢指針,快指針每次走兩步,慢指針每次一步,如果有環,快指針會轉圈,快指針就會等於滿指針)
# 節點
class Node(object):
    def __init__(self, elem):
        self.elem = elem
        self.next = None

# 鏈表
class SingleList(object):
    def __init__(self, head):
        self.head = head
	
	# 判斷是否有環
    def isHasLoop(self, head):
        low, fast = head, head
        while fast and fast.next:
            low = low.next
            fast = fast.next.next
            if low == fast:
                return True
        return False


if __name__ == '__main__':
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = head.next.next
    singleList = SingleList(head)
    print(singleList.isHasLoop(singleList.head))


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章