python使用插入法实现链表反转

# encoding=utf-8


class LNode(object):
    def __init__(self, x):
        self.data = x
        self.next = None


def reverse(head):
    if head is None or head.next is None:
        return
    cur = None
    next = None
    cur = head.next.next
    head.next.next = None
    while cur:
        next = cur.next
        cur.next = head.next
        head.next = cur
        cur = next


if __name__ == "__main__":
    i = 1
    head = LNode(i)
    head.next = None
    tmp = None
    cur = head
    while i < 8:
        tmp = LNode(i)
        tmp.next = None
        cur.next = tmp
        cur = tmp
        i += 1
    print("----------------before reverse----------------")
    cur = head.next
    while cur:
        print(cur.data)
        cur = cur.next

    print("----------------after reverse----------------")
    reverse(head)
    cur = head.next
    while cur:
        print(cur.data)
        cur = cur.next

输出

----------------before reverse----------------
1
2
3
4
5
6
7
----------------after reverse----------------
7
6
5
4
3
2
1
原文地址:https://www.cnblogs.com/byron0918/p/10204783.html