链表记录了头节点与尾节点,是为了方便末尾添加时,不在遍历链表而设置的。反转的思想是设置一个前驱节点为None,首节点指向None,下一个节点指向前一个节点即可。
class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return f'<Node:{self.data}>'
class LinkedList(object):
def __init__(self):
self.head = None
self.last = None
def is_empty(self):
if not self.head:
return True
def append(self, data):
if self.is_empty():
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
# cur = self.head
# while cur.next:
# cur = cur.next
# cur.next = Node(data)
def iter_node(self):
cur = self.head
while cur:
print(cur)
cur = cur.next
def last_node(self):
return self.last
def reverse(self):
# 前驱节点
pre = None
# 当前节点
cur = self.head
# 头尾节点交换
self.head, self.last = self.last, self.head
while cur:
# 记录后驱节点
tmp = cur.next
# 后驱节点指向前驱节点
cur.next = pre
# 当前节点成为前驱节点
pre = cur
cur = tmp
# A -> B -> C -> D
l = LinkedList()
l.append('A')
l.append('B')
l.append('C')
l.append('D')
l.iter_node()
l.reverse()
l.iter_node()
# D -> C -> B -> A