leetcode——61. 旋转链表

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return 
        if head.next==None:
            return head
        if k==0:
            return head
        q=head
        m=0
        while q:
            m+=1
            q=q.next
        n=k%m
        while n:
            q=head
            p=q.next
            while p.next!=None:
                q,p=q.next,p.next
            p.next=head
            q.next=None
            head=p
            n-=1
        return head
执行用时 :44 ms, 在所有 python 提交中击败了14.88%的用户
内存消耗 :11.8 MB, 在所有 python 提交中击败了26.96%的用户
 
——2019.10.25
 

public ListNode rotateRight(ListNode head, int k) {
        if(k == 0){
            return head;
        }
        if(head == null || head.next == null){
            return head;
        }
        int len = 0;  //链表长度>=2
        ListNode p = head;
        while(p != null){
            len ++;
            p = p.next;
        }   //得到链表的长度len
        //进行移动
        int x = k%len;
        while (x--!=0){
            head = rotate(head);
        }
        return head;

    }

    private ListNode rotate(ListNode head) {  //将尾结点移动到头结点
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy;
        while (head.next!=null){
            head = head.next;
            prev = prev.next;
        }
        head.next = dummy.next;
        dummy.next = head;
        prev.next = null;
        return dummy.next;
    }

 

 

虽然做出来了,但是效果并不是很好;

 


 

public ListNode rotateRight(ListNode head, int k) {
        //特殊情况判断
        if(head == null || head.next ==null){
            return head;
        }
        //把环相连同时计算链表长度
        int length = 1;
        ListNode tail = head;
        while(tail.next != null){
            length++;
            tail = tail.next;
        }
        tail.next = head;
        //计算在哪个几点进行断开
        int step = length - k%length -1;
        while(step > 0){
            head = head.next;
            step --;
        }
        //找到newHead并断开
        ListNode newHead = head.next;
        head.next = null;
        return newHead;
    }

 

 

 

——2020.7.14

 
posted @ 2019-10-25 10:28  欣姐姐  阅读(174)  评论(0编辑  收藏  举报