[leetcode]Rotate List @ Python

时间:2023-03-09 09:28:28
[leetcode]Rotate List @ Python

原题地址:https://oj.leetcode.com/problems/rotate-list/

题意:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

解题思路:循环右移一条链表,比如k=2,(1,2,3,4,5)循环右移两位变为(4,5,1,2,3)。由于k值有可能比链表长度大很多,所以先要用一个count变量求出链表的长度。而k%count就是循环右移的步数。

代码:

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def rotateRight(self, head, k):
if k == 0:
return head
if head == None:
return head
dummy = ListNode(0)
dummy.next = head
p = dummy
count = 0
while p.next:
p = p.next
count += 1
p.next = dummy.next
step = count - ( k % count )
for i in range(0, step):
p = p.next
head = p.next
p.next = None
return head