"""
给定单链表1->2->3->4->5->6->7,k=3,那么旋转后的单链表变为5->6->7->1->2->3->4
"""
class LNode:
def __init__(self):
self.data = None
self.next = None
def RotateK(head, k):
"""
方法功能:把链表右旋k个位置
"""
if head is None or head.next is None:
return
# fast指针先走k步,然后与slow指针同时向后走
fast, slow, tmp = LNode(), LNode(), LNode()
slow, fast = head.next, head.next
i = 0
while i < k and fast is not None:
fast = fast.next
i += 1
# 判断k是否已经超过链表的长度
if i < k:
return
# 循环结束后slow指向链表倒数第k+1个元素,fast指向链表最后一个元素
while fast.next is not None:
slow = slow.next
fast = fast.next
tmp = slow
slow = slow.next
tmp.next = None
fast.next = head.next
head.next = slow
def ConstructList():
i = 0
head = LNode()
tmp = None
cur = head
while i < 8:
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
i += 1
return head
def PrintList(head):
cur = head.next
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
if __name__ == '__main__':
head = ConstructList()
print('旋转前:')
PrintList(head)
RotateK(head, 3)
print('\n旋转后')
PrintList(head)
运行结果如下:
旋转前:
0 1 2 3 4 5 6 7
旋转后
5 6 7 0 1 2 3 4