主体思想都是构建环形链表
解法1:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
res=ListNode(-1)
res.next=head
count=0
while res.next:#计算链表长度
count=count+1
res=res.next
if count==0:
return head
res.next=head#构建环形链表
pos=count-k%count-1#目标节点的前驱位置
for i in range(pos):
head=head.next #指向新链表的尾指针
l=head.next# 存储头指针
head.next=None
return l
解法2:通过list直接索引
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
res=ListNode(-1)
res.next=head
postion=[]
while res.next:
res=res.next
postion.append(res)
count=len(postion)
if count==0 or count==1 or k%count==0:
return head
res.next=head#环形
pos=count-k%count#目标节点的位置
postion[pos-1].next=None
return postion[pos]
解法3:双指针,快慢指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
res=ListNode(-1)
res.next=head
first=second=head
count=0
while res.next:
res=res.next
count=count+1
if count==0 or count==1 or k%count==0:
return head
for i in range(k%count):
first=first.next
while first.next:
first=first.next #循环结束first指向最后一个节点
second=second.next #second指向旋转后链表的最后一个节点
first.next=head #构建环形链表
head=second.next #记录头指针
second.next=None
return head