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:
    Given 1->2->3->4->5->NULL and k = 2,
    return 4->5->1->2->3->NULL.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    //关键在于找到旋转节点pivot,pivot.next成为新的头,pivot成为新的尾,而原list的尾后面接上原list的头
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            
            if(head==null) return head;
            
            int length = 0;
            ListNode myNode = head;
            while(myNode != null){              //利用循环求得list的长度
                length++;
                myNode = myNode.next;
            }
            
            if(k >= length) k = k % length;    //此处注意,k是有可能大于长度的
            if(length<=1 || k==0) return head; //此两种情况都不用旋转,直接返回即可
            
            int pivot = length - 1 - k;        //旋转点位置,题目示例中,pivot=2,代表list中第三个节点
            ListNode newHead = null;
            myNode = head;                     //重复利用myNode
            for(int i=0; i<length; i++){
                if(i == pivot){
                    newHead = myNode.next;     //新的头
                    myNode.next = null;        //新的尾
                    myNode = newHead;          //让for循环继续下去
                }
                if(myNode.next != null){       //过了pivot也让循环继续下去,是为了取得原先list的尾
                    myNode = myNode.next;
                }
            }
            myNode.next = head;                //此时,myNode为原list的尾,将其接上原list的head
            
            return newHead;
        }
    }


  • 相关阅读:
    根据坐标点画图形
    js 解析geojson格式
    devexpress 安装
    DataTable 获取列名
    ADO.NET 注册
    css:outline
    javascript函数sort
    引用类型-2015/10/06
    2015-11-02-js
    jquery
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444419.html
Copyright © 2011-2022 走看看