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;
        }
    }
  • 相关阅读:
    Netsharp下微信菜单以及OAuth
    权限管理
    java面向对象基础(转)
    闲来无事做了一个批处理的win10账号管理
    bat获取系统时间修改系统密码
    bat常用命令
    bat修改密码
    vbs的一些入门基础。。。
    WCF 之 DataContract
    WCF 之 OperationContract
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810773.html
Copyright © 2011-2022 走看看