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
喜欢就支持一下吧