1. 題目描述
- 旋轉鏈表
給定一個鏈表,旋轉鏈表,將鏈表每個節點向右移動 k 個位置,其中 k 是非負數。
示例 1:
輸入: 1->2->3->4->5->NULL, k = 2
輸出: 4->5->1->2->3->NULL
解釋:
向右旋轉 1 步: 5->1->2->3->4->NULL
向右旋轉 2 步: 4->5->1->2->3->NULL
示例 2:
輸入: 0->1->2->NULL, k = 4
輸出: 2->0->1->NULL
解釋:
向右旋轉 1 步: 2->0->1->NULL
向右旋轉 2 步: 1->2->0->NULL
向右旋轉 3 步: 0->1->2->NULL
向右旋轉 4 步: 2->0->1->NULL
2. 代碼實現
方法:先將鏈表形成一個閉環,找到最後一個節點和首節點位置,形成一個新的單鏈表。
執行用時 :32 ms, 在所有 Python 提交中擊敗了40.30%的用戶
內存消耗 :12.8 MB, 在所有 Python 提交中擊敗了11.11%的用戶
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
current = head
lens = 1
while current.next:
current = current.next
lens += 1
# 形成閉環
current.next = head
temp = head
lastnode = lens - k%lens-1
# 獲得最後一個節點
for i in range(lastnode):
temp = temp.next
newhead = temp.next
temp.next = None
return newhead