博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode | Rotate List
阅读量:4599 次
发布时间:2019-06-09

本文共 1048 字,大约阅读时间需要 3 分钟。

 

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

转载于:https://www.cnblogs.com/dosmile/p/6444419.html

你可能感兴趣的文章
mac os x mysql 出现./mysql: unknown variable 'sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABL 问题...
查看>>
桐桐的贸易--WA
查看>>
历届试题 高僧斗法
查看>>
linux命令系列 stat & touch
查看>>
[Tools] Webstorm Github的配置与使用
查看>>
鬼谷子绝学
查看>>
Mongodb 笔记04 特殊索引和集合、聚合、应用程序设计
查看>>
使用Post/Redirect/Get实现Asp.net防止表单重复提交
查看>>
用Html5与Asp.net MVC上传多个文件
查看>>
lambda函数,常用函数,内置函数(string,zip()map()filter())的用法
查看>>
Xcode中匹配的配置包的存放目录
查看>>
JavaScript将具有父子关系的原始数据格式化成树形结构数据(id,pid)
查看>>
CSS3.0——背景属性
查看>>
【转载】C语言中的undefined behavior/unspecified behavior - 序
查看>>
MySQL服务使用
查看>>
C语言练手自己编写学生成绩管理系统
查看>>
20175204 张湲祯 2018-2019-2《Java程序设计》第二周学习总结
查看>>
NCPC 2015 - Problem A - Adjoin the Networks
查看>>
How to lisp Lisp output a paragraph"500 Tph Dry Process Cement Plant Machinery Manufacturers"
查看>>
更改chrome浏览器css背景为护眼色,更改字体为微软雅黑。
查看>>