鏈表的逆置


鏈表是一個特殊的數據結構,其中每個節點包含自己的數據以及下一個值的引用(指針),鏈表的逆置就是指將鏈表下一個值的引用(指針)調換,如下圖所示:

 

 

 鏈表的節點的結構如下:

 

 data為自定義的數據,next為下一個節點的地址

一 構造鏈表

class Node(object):
    def __init__(self, value, next):
        self.value = value
        self.next = next


head = Node('頭', None)
last = head
l = ['涉哥', '剛哥', '雷哥', '強哥']
for i in l:
    node = Node('%s' % i, None)
    last.next = node
    last = node

# ######### 查看鏈表關系 ##########
print('原始鏈表信息為%s'%head.value)
print(head.next.value)
print(head.next.next.value)
print(head.next.next.next.value)
print(head.next.next.next.next.value)

 

第二步 鏈表逆置 

 

 

def reverse_linked_list(head):
    """
    鏈表逆置
    :param head:
    :return:
    """
    if not head or not head.next:
        return head

    prev_node = None
    current_node = head
    next_node = head.next

    while True:
        current_node.next = prev_node    # 變箭頭
        if not next_node:
            break
        prev_node = current_node
        current_node = next_node
        next_node = current_node.next
    return current_node


new_head = reverse_linked_list(head)        

print('逆置之后的鏈表')
print(new_head.value)
print(new_head.next.value)
print(new_head.next.next.value)
print(new_head.next.next.next.value)
print(new_head.next.next.next.next.value)

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM