[Lintcode] 170. Rotate List/[Leetcode]61. Rotate List

170. Rotate List/61. Rotate List

  • 本题难度: Medium
  • Topic: Linked List

Description

Given a linked list, remove the nth node from the end of list and return its head.

Example
Example 1:
Input: list = 1->2->3->4->5->null, n = 2
Output: 1->2->3->5->null

Example 2:
Input: list = 5->4->3->2->1->null, n = 2
Output: 5->4->3->1->null

Challenge
Can you do it without getting the length of the linked list?

Notice
The minimum number of nodes in list is n.

我的代码

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: the List
    @param k: rotate to the right k places
    @return: the list after rotation
    """
    def rotateRight(self, head, k):
        # write your code here
        #1.逻辑
        #2.特殊情况
        #2.1 null
        #2.2 k == 0
        #2.3 大于len的情况
        if k==0 or head is None:
            return head
        count = 0
        l1 = l2 = head
        while(k>0):
            count += 1
            l2 = l2.next
            k = k-1
            if l2 == None:
                l2 = head
                k %= count
        if l1 == l2:
            return head
        while(l2.next):
            l1 = l1.next
            l2 = l2.next
        res = l1.next
        l1.next = None
        l2.next = head
        return res

思路

设两个指针,期间相隔n,当前一个指针到链尾时,返回另一个指针。

需要考虑的问题:

  1. 当链表为空时
  2. 除去链头元素时。

在leetcode中上面的代码没通过。
Lintcode 可以通过但是Leetcode不行,超时。

l1 = l2 = head
while(k>0):
    l2 = l2.next
    k = k-1
    if l2 == None:
        l2 = head

所以加了一个衡量链表长度的值,模之后,减少了运算时间。

在leetcode中上面的代码没通过,time limit,所以加了一个衡量链表长度的值,模之后,减少了运算时间。

在leetcode中上面的代码没通过,time limit,所以加了一个衡量链表长度的值,模之后,减少了运算时间。

count = 0
l1 = l2 = head
while(k>0):
    count += 1
    l2 = l2.next
    k = k-1
    if l2 == None:
    l2 = head
    k %= count
  • 时间复杂度 O(n)
  • 出错
    特殊情况太多了。要注意。

转载于:https://www.cnblogs.com/siriusli/p/10365580.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值