鏈表反轉(zhuǎn)

#!/usr/bin/env python

class ListNode:
    def __init__(self, value=0, next=None):
        self.val = value
        self.next = next

def create_list(values):
    head = None
    for value in values[::-1]:
        head = ListNode(value,head)
    return head

def create_list2(values):
    head = None
    pre = None
    for i in range(0,len(values),1):
        cur = ListNode(values[i],None)
        if pre is not None:
            pre.next = cur
            pre = cur
        else:
            head = cur
            pre = cur
    return head

def print_list(head):
    val = ""
    cur = head

    while cur is not None:
        val = val + str(cur.val) + '->'
        cur = cur.next
    val = val + 'Null'
    print(val)

def reverse_list(head):
    if head is None or head.next is None:
        return head
    new_head = reverse_list(head.next)
    head.next.next = head
    head.next = None
    return new_head

def reverse_list2(head):
    pre = None
    cur = head
    next_node = None
    while cur is not None:
        next_node = cur.next
        cur.next = pre
        pre = cur
        cur = next_node
    return pre


if __name__ == '__main__':    
    values = [1,2,3,4,5]
    list = create_list2(values)
    print_list(list)
    print_list(reverse_list(list))

    list2 = create_list2(values)
    # print_list(list2)
    print_list(reverse_list2(list2))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容