实现单链表的倒置(两种方法)
# conding:utf8 class Node(): def __init__(self, _item): self.item = _item self.next = None class Link(): def __init__(self): self._head = None def append(self, _item): node = Node(_item) cur = self._head pre = None if cur == None: self._head = node return while cur: pre = cur cur = cur.next pre.next = node def travel(self): cur = self._head while cur: print(cur.item) cur = cur.next # 方式一:三个变量实现单链表倒置 def reverse1(self): pre = None cur = self._head next_node = cur.next while cur: cur.next = pre pre = cur cur = next_node if next_node: next_node = next_node.next self._head = pre # 方式二:两个变量实现单链表的倒置 def reverse2(self): pre = None cur = self._head while cur: temp = cur.next cur.next = pre pre = cur cur = temp self._head = pre if __name__ == "__main__": link = Link() link.append(1) link.append(2) link.append(3) link.travel() print("---------------------------") link.reverse1() link.travel()
输出结果:
1 2 3 --------------------------- 3 2 1