zoukankan      html  css  js  c++  java
  • [leetcode] Rotate List

    Given a list, rotate the list to the right by k places, where k is non-negative.

    For example:
    Given1->2->3->4->5->NULLand k =2,
    return4->5->1->2->3->NULL.

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

    思路1:先遍历一遍求长度,然后从头再开始走k%len步,设置新的头尾节点,连接原来的头尾节点。

    思路2:遍历求长度,将首尾连接,继续走到新的头尾,断开。

    思路1代码:

    public class Solution {
        public ListNode rotateRight(ListNode head, int n) {
            if (head == null)
                return null;
            int len = 0;
            ListNode p = head;
            while (p != null) {
                len++;
                p = p.next;
            }
            
            p = head;
            int i;
            n = n % len;
            if (n == 0)
                return head;
            for (i = 0; i < len - n - 1; i++)
                p = p.next;
            ListNode newTail = p;
            ListNode newHead = p.next;
    
            while (p.next != null)
                p = p.next;
            p.next = head;
            newTail.next = null;
            return newHead;
    
        }
    
        public static void main(String[] args) {
            ListNode head = ListUtils.makeList(1, 2, 3, 4, 5);
            ListUtils.printList(head);
            head = new Solution().rotateRight(head, 2);
            ListUtils.printList(head);
        }
    }

    第二遍记录:

      改了个小地方,第一遍求长度的时候,顺便把头尾连接起来。

    public class Solution {
        public ListNode rotateRight(ListNode head, int n) {
            if(head==null)
                return null;
            int len=1;
            ListNode p = head;
            while(p.next!=null){
                len++;
                p=p.next;
            }
            p.next=head;
            
            n = n%len;
            p=head;
            for(int i=0;i<len-1-n;i++){
                p=p.next;
            }
            ListNode newHead =p.next;
            p.next=null;
            return newHead;
        }
    }
  • 相关阅读:
    UML序列图
    接口初探
    Discuz初探
    Vim指令学习
    UCenter Home代码研读之space.php
    建站须知
    linux指令之文件的创建、查询、修改
    InitPHP初探
    php环境搭建
    Zend Framework学习之Zend_Db 数据库操作
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810773.html
Copyright © 2011-2022 走看看