题解 | #牛群旋转#
牛群旋转
https://www.nowcoder.com/practice/5137e606573843e5bf4d8ea0d8ade7f4
- 题目考察的知识点 : 链表构建环,断开链表
- 题目解答方法的文字分析:
- 统计链表长度 n,连接尾节点和头节点构成环
- 移动到指定位置n- k断开
- 返回新的头节点
- 本题解析所用的编程语言:Python
- 完整且正确的编程代码
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def rotateLeft(self , head: ListNode, k: int) -> ListNode:
if not head:
return None
n = 1
tail = head
while tail.next:
n += 1
tail = tail.next
tail.next = head # 构建环
for _ in range(n - k%n):
tail = tail.next
result = tail.next
tail.next = None
return result
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路
查看7道真题和解析