单链表的反转 python实现实例

单链表反转实现

1、递归实现

  根据递归,递归到最后一个节点(条件为head3为非空,其下一个指向为空),将其next指向前一个结点,前一个结点的指向为None。

def recurse(head, newhead):  # 递归,head为原链表的头结点,newhead为反转后链表的头结点
        if head is None:
            return
        if head.next is None:
            newhead = head
        else:
            newhead = recurse(head.next, newhead)
            head.next.next = head
            head.next = None
        return newhead

注释:原来链表为{1,2,3,4}

head指向为1,pHead1=head.next   pHead2=pHead1.next    pHead3=pHead2.next

a、递归最后实现newhead=phead3

b、回到上次递归的结束下方

2、循环实现

    def ReverseList(self, pHead):
        if pHead is None or pHead.next is None:
            return pHead
        pre = None
        cur = pHead
        h = pHead
        while cur:
            h = cur
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return h

猜你喜欢

转载自www.cnblogs.com/6530265oule/p/10092534.html