题目描述:给定一个链表,旋转链表,将链表每个节点向右移动 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
解法1。用2个指针,一个走在前面fast,一个走在后面slow。统计出链表长度后更新k,fast先走k步,再一起走,slow.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:
return
le = head
len_l = 0
while le:
le = le.next
len_l += 1
k %= (len_l) # 该移几位
slow = head
fast = head
for i in range(k):
if fast:
fast = fast.next
if not fast:
return head
while fast.next:
fast = fast.next
slow = slow.next
fast.next = head
fast = slow.next
slow.next = None
return fast
解法2。先首尾相连构成环,再从尾节点开始往后走n-k%n步,当前节点的next就是新的头结点,再从此处断开
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return
le = head
len_l = 1
while le.next:
le = le.next
len_l += 1
le.next = head
m = len_l - k%len_l # 以下这段也适用于长度为1或2的测试用例,亲测
for i in range(m):
le = le.next
new_head = le.next
le.next = None
return new_head