美文网首页
python实现单向链表的反转

python实现单向链表的反转

作者: 徐德东 | 来源:发表于2018-06-22 15:00 被阅读0次

    # -*- encoding:utf-8 -*-

    """

    @author: dedong.xu

    @date: 2018/03/22

    @description: 单向链表的反转

    """

    class ListNode(object):

        def __init__(self, value, n=None):

            self.value = value

            self.next = n

    def recurse(head, newhead=None):

        if headis None:

            return

        if head.next is None:

            newhead = head

        else:

            newhead = recurse(head.next, newhead)

            head.next.next = head

            head.next =None

        return newhead

    if __name__ == "__main__":

        head = ListNode(1)

        p1 = ListNode(2)

        p2 = ListNode(3)

        p3 = ListNode(4)

        p4 = ListNode(5)

        p5 = ListNode(6)

        head.next = p1

        p1.next = p2

        p2.next = p3

        p3.next = p4

        p4.next = p5

        p = recurse(head, newhead=None)

        while p:

            print p.value,

            p = p.next

    相关文章

      网友评论

          本文标题:python实现单向链表的反转

          本文链接:https://www.haomeiwen.com/subject/phmkyftx.html