今天做到了反转链表,就想着运用前几天学的东西,重新复盘一下,最后发现还是有些模棱两可的地方,说明以往的学习都是在自我安慰,没有将逻辑内化为自身的知识。
# -*- coding: utf-8 -*-
"""
@Time : 2022/8/12 15:54
@Author : FJC
@File : 反转链表.py
@Software: win10 python3.7
"""
class Node:
def __init__(self,val,next=None):
self.val = val
self.next=next
class Solution:
def __init__(self):
self._head=None
def add(self,val):
node=Node(val)
if self._head==None:
self._head=node
else:
node.next = self._head
self._head=node
def append(self,val):
node=Node(val)
if self._head==None:
self.add(val)
else:
cur=self._head # 此时的cur为node
while cur.next!=None:
cur=cur.next
cur.next=node
def travel(self):
cur=self._head
while cur!=None: # 此时为cur.next则会刚好运行到最后一个节点,但由于cur.next=None,则不执行下面语句
print(cur.val,end=" ")
cur=cur.next
def reverseList(self):
cur=self._head
pre=None
while cur!=None:
transit=cur.next
cur.next=pre
pre=cur
cur=transit
while pre != None:
print(pre.val,end=" ")
pre=pre.next
solution=Solution()
solution.add(3)
solution.add(2)
solution.add(1)
solution.append(4)
solution.append(5)
solution.travel()
print()
solution.reverseList()