反转单向链表 demo
# reverseLinkedList.py
# 2021年9月19日15:43:19 星期日 中秋快乐
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
# a -> b -> c -> D -> None
# d -> c -> b -> a -> None
def reverseLinkedList(head):
curr = head
previous = None
while curr != None:
tmp_next = curr.next
curr.next = previous
previous = curr
curr = tmp_next
return previous
class LinkedList:
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def append(self, item):
node = Node(item)
if self.is_empty():
self._head = node
else:
cur = self._head
while cur.next is not None:
cur = cur.next
cur.next = node
def show(self):
cur = self._head
while cur is not None:
print(cur.item+" -> ", end='')
cur = cur.next
print('None')
def items(self, head):
cur = head
while cur is not None:
print(cur.item+" -> ", end='')
cur = cur.next
print('None')
if __name__=="__main__":
list=['a', 'b', 'c', 'e', 'f']
link_list = LinkedList()
for i in list:
link_list.append(i)
link_list.show()
link_list2 = reverseLinkedList(link_list._head)
LinkedList().items(link_list2)
运行效果
$ python reverseLinkedList.py
a -> b -> c -> e -> f -> None
f -> e -> c -> b -> a -> None
网友评论