本文主要是介绍Leetcode 61. 旋转链表 Python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我的版本:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution(object):def rotateRight(self, head, k):""":type head: ListNode:type k: int:rtype: ListNode"""node = headcnt = 0# 计算链表长度while node:cnt += 1node = node.next# 保持原地不动:无需移动的情况if cnt <= 1 or k%cnt ==0:return headk %= cntj = cnt - kdummy = ListNode(0)cur = dummynode = headwhile j > 0:cur.next = ListNode(node.val)cur = cur.nextnode = node.nextj -= 1res = nodewhile node.next:node = node.next node.next = dummy.nextreturn res
大神版本:
def rotateRight(self, head, k):if k == 0 or head is None:return headdummy=ListNode(0)dummy.next=headp=dummylength=0while p.next: # 得到list的长度length+=1p=p.nextp.next=dummy.next # 指针指向headstep=length-(k%length) # 得到新head的位置while step>0: # 到新head的位置step-=1p=p.nextdummy.next=p.next # 变化p.next=None #return dummy.next
这篇关于Leetcode 61. 旋转链表 Python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!