python链表的应用(python链表实现左移和右移)
导读:1、对于链表调用rotate(n 方法来重载左移、右移(相应的内置方法__lshift__和__rshift__ 。...
1 、对于链表调用rotate(n)方法来重载左移 、右移(相应的内置方法__lshift__和__rshift__) 。
def__lshift__(self,n): returnself.rotate(n) def__rshift__(self,n): returnself.rotate(-n)2 、涉及到该操作的链表并没有改变 ,要更改该值的使用>>=或<=进行赋值 。
也可以直接向代码中添加覆盖原链表的代码 。
def__lshift__(self,n): ret=self.rotate(n) self.val,self.next=ret.val,ret.next returnret def__rshift__(self,n): ret=self.rotate(-n) self.val,self.next=ret.val,ret.next returnret >>>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基础教程
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!