Python数据结构:1.单链表反转

单链表的反转

1.非递归方式

cur指向当前结点,使用pre指向前一个结点,每次把cur->next指向pre即可

# -*- coding: utf-8 -*-


class LNode:
    def __init__(self, elem, next_=None):
        self.elem = elem
        self.next_ = next_


class LList:
    def __init__(self, _head=None):
        self._head = _head

    def no_recursive_reverse(self):
        if self._head is None or self._head.next_ is None:
            return self._head
        pre = None
        cur = self._head
        h = cur
        while cur:
            h = cur
            tmp = cur.next_
            cur.next_ = pre
            pre = cur
            cur = tmp
        return h


if __name__ == '__main__':
    head = LNode(1)
    p = head
    for i in range(2, 10):
        p.next_ = LNode(i)
        p = p.next_
    obj = LList(head)
    q = obj.no_recursive_reverse()
    while q:
	    print q.elem
	    q = q.next_

2.递归方式

# -*- coding: utf-8 -*-


class LNode:
    def __init__(self, elem, next_=None):
        self.elem = elem
        self.next_ = next_


class LList:
    def __init__(self, _head=None):
        self._head = _head

    @staticmethod
    def recursive_reverse(old_head, new_head):
        if old_head is None:
            return
        if old_head.next_ is None:
            new_head = old_head
        else:
            new_head = LList.recursive_reverse(old_head.next_, new_head)
            old_head.next_.next_ = old_head
            old_head.next_ = None
        return new_head


if __name__ == '__main__':
    head = LNode(1)
    p = head
    for i in range(2, 10):
        p.next_ = LNode(i)
        p = p.next_
    new_head_none = None
    q = LList().recursive_reverse(head, new_head_none)
    while q:
        print q.elem
        q = q.next_

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值