leetcode笔记--Rotate List

来源:互联网 发布:js 如何遍历数组对象 编辑:程序博客网 时间:2024/06/05 19:43

题目:难度(Medium)

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
    Given 1->2->3->4->5->NULL and k = 2,
    return 4->5->1->2->3->NULL.
Tags:Linked List Two Pointers
Similar Problems:(E) Rotate Array

分析:k是一个非负整数,将链表向右旋转k个元素,即将右边k个节点拿到链表的前面,也就是说把链表的前len-k+1个节点拿到链表的后面去。如果k%len == 0的话,链表旋转以后还是会还原,则直接返回链表即可,否则,将链表分成2段,前一段为len-k+1个节点,p为第1段的尾节点,q为整个链表的尾节点也是第2段的尾节点,将第2段与第1段链接起来:q.next = head,那么新的头节点应该为第2段的头节点位置即p.next,新的尾节点即为第1段的尾节点p,即p.next = None

代码实现:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def rotateRight(self, head, k):        """        :type head: ListNode        :type k: int        :rtype: ListNode        """        if head is None:            return None                            #找到新的头节点、尾节点p,断开新的尾节点与新头节点(新尾节点是新头节点的前驱),连上旧的尾节点q与旧头节点        #新的头节点的位置是正向第len-k+1的位置        len = self.getLenOfSinglyLinkedList(head)        #k == 0 或者 k == len 或者 k是len的整数倍        if k%len == 0:            return head                    pos = len - k%len        count = 1        p = head        while count < pos:            p = p.next            count+=1        #此时p为新的尾节点        #继续找到旧尾节点位置        q = p        while q.next is not None:            q = q.next        #此时q为旧尾节点位置        q.next = head        head = p.next        p.next = None        return head        def getLenOfSinglyLinkedList(self, head):        p = head        len = 0        while p:            p = p.next            len+=1        return len


0 0