如何将单链表向右旋转k个位置

"""
给定单链表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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值