• 技术文章 >Python技术 >Python基础教程

    python链表实现左移和右移

    小妮浅浅小妮浅浅2021-09-10 09:21:54原创2817

    1、对于链表调用rotate(n)方法来重载左移、右移(相应的内置方法__lshift__和__rshift__)。

    1

    2

    3

    4

    5

    def __lshift__(self, n):

        return self.rotate(n)

     

    def __rshift__(self, n):

        return self.rotate(-n)

    2、涉及到该操作的链表并没有改变,要更改该值的使用>>=或<=进行赋值。

    也可以直接向代码中添加覆盖原链表的代码。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

        def __lshift__(self, n):

            ret = self.rotate(n)

            self.val,self.next = ret.val,ret.next

            return ret

      

        def __rshift__(self, n):

            ret = self.rotate(-n)

            self.val,self.next = ret.val,ret.next

            return ret

      

    '''

    >>> node = Node.build(1,2,3,4,5)

    >>> node

    Node(1->2->3->4->5->None)

    >>> node >> 1

    Node(5->1->2->3->4->None)

    >>> node >> 2

    Node(3->4->5->1->2->None)

    >>> node >> 3

    Node(5->1->2->3->4->None)

    >>> node

    Node(5->1->2->3->4->None)

    >>> node << 6

    Node(1->2->3->4->5->None)

    >>> node << 1

    Node(2->3->4->5->1->None)

    >>> node << 1

    Node(3->4->5->1->2->None)

    >>> node >> 2

    Node(1->2->3->4->5->None)

    >>> node

    Node(1->2->3->4->5->None)

    >>>

    '''

    以上就是python链表实现左移和右移的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python链表
    上一篇:python链表的乘法问题 下一篇:Python绘图项目之海绵宝宝

    相关文章推荐

    • 什么是网络协议• python中的去除重复项的操作• python中少见的函数map()和partial()• python的sort()排序方法• Python中的文件读写-理论知识

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网