单链表反转

回顾一下"单链表反转"

初始化一个链表

使用py的类模拟实现

class LinkNode:
    def __init__(self, data):
        self.data = data
        self.next = None


def init(s='ABCD'):
    head = LinkNode(None)
    p = head
    for v in s:
        p.next = LinkNode(v)
        p = p.next
    return head.next

def show(link):
    while link:
        print('{} ->'.format(link.data), end=' ')
        link = link.next
    print('None')

原地反转

上一步初始化了一个单链表:

A -> B -> C -> D -> None

原地反转就是链表头开始依次反转每个节点,以下是反转步骤

None <- A    B -> C -> D -> None
None <- A <- B    C -> D -> None
None <- A <- B <- C    D -> None
None <- A <- B <- C <- D    None

代码实现如下

def reverse(link):
    prev = None
    cur = link
    while cur:
        tmp = cur.next
        cur.next = prev
        prev = cur
        cur = tmp
    # 此时 cur 已经是 None 所以返回 prev
    return prev

头插法

头插法就是从原链表头开始,依次取出每个节点,然后插到一个新链表的头节点后

新: head -> None
原: A -> B -> C -> D -> None

新: head -> A -> None
原: B -> C -> D -> None

新: head -> B -> A -> None
原: C -> D -> None

新: head -> C -> B -> A -> None
原: D -> None

新: head -> D -> C -> B -> A -> None
原: None

代码实现如下

def reverse2(link):
    head = LinkNode(None)
    while link:
        tmp = link.next
        link.next = head.next
        head.next = link
        link = tmp
    # 新链表头节点的下一个节点为原链表的尾节点
    return head.next
原文地址:https://www.cnblogs.com/wbjxxzx/p/11360728.html