LeetCode 61. Rotate List(Python详解及实现)

来源:互联网 发布:淘宝网家电电器品种 编辑:程序博客网 时间:2024/04/25 13:08

【题目】

Given a list, rotate the list to the rightby k places, where k is non-negative.

 

For example:

Given 1->2->3->4->5->NULLand k = 2,

return 4->5->1->2->3->NULL.

给定一个链表,将链表末尾的k个结点移动到最前面。

【思路】

方法一:

先遍历一次求长度,然后再求模得到真正右移数量

方法二:

采用bef、af 指针的方法(前后指针),令bef指针先移动k步,步长为1。然后两个指针同时移动,当bef指针到达最末尾时,将bef指向head,af指向None,则完成旋转。

注:题目中的k有可能大于链表总长度,因此需要对k取模。

 

【Python实现】

方法一:

# 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 head == None or k == 0:

           return head

       dummy = ListNode(0)#创建一个虚假的头结点

       dummy.next = head #虚假头结点指向head

       #计算链表长度

       count = 0

       p = dummy

       while p.next != None:

           p = p.next#最终P将指向尾节点

           count += 1

       

       p.next = dummy.next#将尾结点指向头结点,形成环形

       #求真实的右移数量

       right = count - k % count

       p = dummy.next#指向head

       for i in range(1,right):#i = 1 时,p为链表的第2个数据

           p = p.next

       head = p.next#移动后的头结点

       p.next = None

       return head

 

方法二:

# 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 head == None or head.next == None or k == 0: 

           return head 

       count = 0 

       p = head 

       while(p): 

           count += 1 

           p = p.next 

       k = k % count#真实旋转值k 

       if k == 0: 

           return head 

       p = head 

       while(k > 0):#执行完p为链表第k+1个结点 

           k -= 1 

           p = p.next 

       af = head #af为头结点

       bef = p  #bef为当前p

       while bef.next:  #将bef移到链表尾结点的同时,af也向尾结点方向移

           af = af.next  #bef移到尾结点的同时,af指向旋转后的尾结点

           bef = bef.next           

       new_head = af.next #旋转后的尾结点的下一个结点即为新链表的头结点 

       bef.next = head  #原链表的尾结点指向原头结点

       af.next = None  #旋转后的尾结点指向None

       return new_head

    

原创粉丝点击