Python实现链表倒排(循环法)

一、代码如下

1、倒排函数

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

def reverseList_loop(head: ListNode) -> ListNode:
    if head is None or head.next is None:
        return head

    prev = None
    curr = head
    h = head
    while curr:
        h = curr
        tmp = curr.next
        curr.next = prev
        prev = curr
        curr = tmp
    return h

2、调用函数

def main():
    # 初始化
    head = ListNode(1)
    p1 = ListNode(2)
    p2 = ListNode(3)
    p3 = ListNode(4)
    p4 = ListNode(5)
    head.next = p1
    p1.next = p2
    p2.next = p3
    p3.next = p4
    newHead = None

    # 调用倒排函数
    result = reverseList_loop(head)

    # 输出结果
    while result:
       print(result.val)
       result = result.next

if __name__ == "__main__":
    main()

你可能感兴趣的:(Python,基础知识,算法,链表,数据结构)