給定乙個鍊錶,旋轉鍊錶,將鍊錶每個節點向右移動 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
1.犧牲一點空間,先把煉表裡的值都放大陣列a中,對陣列做移動,再從a重新構造乙個聊表
2.將鍊錶弄成乙個環,迴圈移動其實就是最終怎麼找到那個head和tail,最後把尾部斷開!
# definition for singly-linked list.
# class listnode(object):
# def __init__(self, x):
# self.val = x
# self.next = none
from collections import deque
class solution(object):
def rotateright(self, head, k):
if not head or not head.next or k==0:
return head
def get_len(t):
count = 0
while t:
count+=1
t=t.next
return count
count = get_len(head)
k = k%count
tmp = deque()
while head:
head = head.next
while k:
t = tmp.pop()
k-=1
newhead = p = listnode(-1)
for one in tmp:
p.next = listnode(one)
p = p.next
return newhead.next
# 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 k==0:
return head
cur = head
tail = none
length = 1
while cur.next:
cur = cur.next
length+=1
loop = length - k%length
tail = cur
cur.next = head
cur = head
for i in range(loop):
cur = cur.next
tail = tail.next
tail.next = none
return cur
61 旋轉鍊錶
給定乙個鍊錶,旋轉鍊錶,將鍊錶每個節點向右移動 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 ...
61,旋轉鍊錶
給定乙個鍊錶,旋轉鍊錶,將鍊錶每個節點向右移動 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 nul...
61 旋轉鍊錶
給定乙個鍊錶,旋轉鍊錶,將鍊錶每個節點向右移動 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 ...