zoukankan      html  css  js  c++  java
  • <LinkedList> 61

    61. Rotate List

    方法一:做k次rotation。

    1.corner case需要考虑

    2.当k远远大于的计算量的时候,记得算出链表长度并对长度求余。

    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null) return null;
            if(head.next == null) return head;
            int n = 0;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode cur = head;
            while(cur != null){
                n++;
                cur = cur.next;
            }
            k %= n;
    
            for(int i = 0; i < k; i++){
                ListNode pre = dummy;
                ListNode last = dummy.next;
                while(last.next != null){
                    pre = pre.next;
                    last = last.next;
                }
                last.next = dummy.next;
                dummy.next = last;
                pre.next = null;
            }
            return dummy.next;
        }
    }

    方法二:

    原理是先遍历整个链表获得链表长度 i ,然后此时把链表头和尾链接起来,在往后走i - k % i个节点就到达新链表的头结点前一个点,这时把 Slow的下一个节点是头节点。

    时间复杂度和空间复杂度都快很多。

    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null || head.next == null) return head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode fast = dummy, slow = dummy;
            
            int i;
            for(i = 0; fast.next != null; i++){
                fast = fast.next;
            }
            
            for(int j = i - k % i; j> 0; j--){
                slow = slow.next;
            }
            fast.next = dummy.next;
            dummy.next = slow.next;
            slow.next = null;
            return dummy.next;
        }
    }
  • 相关阅读:
    逆向学习-内嵌补丁(洞穴代码)
    ubuntu下创建ftp用户,该用户只访问特定目录下的内容
    Ubuntu 14.04 FTP服务器--vsftpd的安装和配置
    Hdu 4223 Dynamic Programming?
    Hdu 3873 Invade the Mars
    Hdu 2025 查找最大元素
    Hdu 1520 Anniversary party
    Hdu 4283 You Are the One
    HTTP协议
    常用正则表达式
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/12190360.html
Copyright © 2011-2022 走看看