• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
鱼市口
博客园    首页    新随笔    联系   管理    订阅  订阅
Leetcode61
!!Given the head of a linked list, rotate the list to the right by k places.!!
 
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head == None:
            return []
        count = 1
        temp = head
        while (temp.next != None):
            count +=1
            temp = temp.next
            # count = length, so the length remaining same seq is count - k -1
 
        if k == 0:return head;
        #else
        head = temp.next
        temp.next = None
        while(count -k -1): #ensure the amount of reversed nodes
            #to reverse
            head = temp.next
            temp.next = None #clearance
            return head
 
A better way:
#先把链表首尾相连,再找到位置断开循环
class Solution(object):
    def rotateRight(self, head, k):
        if head is None or head.next is None: return head
        start, end, len = head, None, 0
        while head:
            end = head
            head = head.next
            len += 1
        end.next = start
        pos = len - k % len
        while pos > 1:
            start = start.next
            pos -= 1
        ret = start.next
        start.next = None
        return ret
posted on 2022-12-24 23:27  鱼市口  阅读(26)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3