首页 > 其他分享 >Leetcode61

Leetcode61

时间:2022-12-24 23:33:21浏览次数:38  
标签:Leetcode61 head return temp None next start

!!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

标签:Leetcode61,head,return,temp,None,next,start
From: https://www.cnblogs.com/selfmade-Henderson/p/17003551.html

相关文章

  • 【算法训练营day20】LeetCode654. 最大二叉树 LeetCode617. 合并二叉树 LeetCode700.
    LeetCode654.最大二叉树题目链接:654.最大二叉树初次尝试和昨天最后一题的思路很像,本质上都是递归构建二叉树。classSolution{public:TreeNode*constructMa......
  • leetcode611
    有效三角形的个数Category Difficulty Likes Dislikesalgorithms Medium(53.27%) 447 -TagsCompanies给定一个包含非负整数的数组nums,返回其中可以组成三角形三条......
  • 好路径数目-Leetcode6191
    好路径数目题目描述给你一棵n个节点的树(连通无向无环的图),节点编号从0到n-1且恰好有n-1条边。给你一个长度为n下标从0开始的整数数组vals,分别表示每......
  • LeetCode617 合并二叉树
    LeetCode617合并二叉树#Definitionforabinarytreenode.#classTreeNode:#def__init__(self,val=0,left=None,right=None):#self.val=val......