leetcode -- Rotate List -- 重点

https://leetcode.com/problems/rotate-list/

这里思路很简单。但是要注意,k可以大于len(linkedlist). 要求得长度之后取mod。还有就是这个rotate,不需要把rotate部分逆置。

    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next: return head
        #calculate the length
        p = head
        count = 0
        while p:
            p = p.next
            count += 1
        k = k % count
        #print (count,k)
        if k == 0: return head

        i,j = head,head
        pre_i = None
        for x in xrange(k-1):  
            j = j.next

        while j.next:
            pre_i = i
            i, j = i.next, j.next
        if i == head:
            return head
        else:
            new_head, new_end = i,j
            new_end.next = head
            pre_i.next = None
            return new_head

由于一开始看错题目,以为rotate的部分要逆置。所以这里还是post出逆置的code。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):

    def reverse(self, head):

        org_head = head
        cur = head.next
        pre = head
        pre.next = None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre, cur =cur, tmp
        return pre, org_head


    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next: return head
        #calculate the length
        p = head
        count = 0
        while p:
            p = p.next
            count += 1
        k = k % count
        print (count,k)
        if k == 0: return head

        i,j = head,head
        pre_i = None
        for x in xrange(k-1):  
            j = j.next

        while j.next:
            pre_i = i
            i, j = i.next, j.next
        if i == head:
            return self.reverse(i)[0]
        else:
            new_head, new_end = self.reverse(i)
            new_end.next = head
            pre_i.next = None
            return new_head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值