python面试之python实现链表反转

python实现链表反转

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

class ListNode:
    def __init__(self):
        self.head=Node()

    def append(self,num):
        node=Node(num)
        cur=self.head
        while cur.next!=None:
            cur=cur.next
        cur.next=node

    def print(self):
        cur=self.head
        while cur.next!=None:
            print('data:',cur.data)
            cur=cur.next
        print('end:',cur.data)

    def reverse(self):
        head=self.head
        cur=head.next.next
        pre=head.next
        pre.next=None
        while cur.next!=None:
            next=cur.next
            cur.next=pre
            pre=cur
            cur=next
        head.next=cur
        cur.next=pre

if __name__ == '__main__':
    list=ListNode()
    for i in range(1,3):
        list.append(i)
    list.print()
    print('翻转')
    list.reverse()
    list.print()
© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发
程序员吾非同的头像-程序员知识精选

昵称

取消
昵称表情代码图片