[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)
  • 出错
    特殊情况太多了。要注意。
posted @ 2019-02-12 16:09  siriusli  阅读(152)  评论(0编辑  收藏  举报