用python语言解答LeetCode的61题
方法一:将链表连成环
方法一的代码:
# coding:utf-8
class LinkNode():
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head, k):
if not head:
return None
if not head.next:
return head
# 将链表形成闭环,同时计算出链表节点个数
old_tail = head
n = 1
while old_tail.next:
old_tail = old_tail.next
n += 1
old_tail.next = head
# 找出新的链表头部和尾部
new_tail = head
for i in range(n - k % n - 1):
new_tail = new_tail.next
# 断开闭环
new_head = new_tail.next
new_tail.next = None
# 返回新的链表
return new_head
方法一的运行结果: