python:添加链表头节点、尾结点、遍历链表、反转链表

今天做到了反转链表,就想着运用前几天学的东西,重新复盘一下,最后发现还是有些模棱两可的地方,说明以往的学习都是在自我安慰,没有将逻辑内化为自身的知识。

# -*- 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()






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值