• [JAVA]用数学解释数组移步问题(新增对链表移步的解释)


    数组移步转载:https://blog.csdn.net/shijing_0214/article/details/53056943


    题目来源:leetcode 2019-03-17

    题目描述:Given a linked list, rotate the list to the right by k places, where k is non-negative.

    链表移步:观察链表移步的规律可以发现,其实就是在一个环里走,然后选一个结点当头就行

    Input: 0->1->2->NULL, k = 4
    Output: 2->0->1->NULL
    Explanation:
    rotate 1 steps to the right: 2->0->1->NULL
    rotate 2 steps to the right: 1->2->0->NULL
    rotate 3 steps to the right: 0->1->2->NULL
    rotate 4 steps to the right: 2->0->1->NULL

    代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode rotateRight(ListNode head, int k) {
    11         if(k==0||head==null) return head;
    12         ListNode cur=head;
    13         int l=1;
    14         while(cur.next!=null)//链表长度
    15         {
    16             ++l;
    17             cur=cur.next;
    18         }
    19         if(k>l) k=k%l;
    20         if(l==k) return head;//步数如果是整数倍直接返回
    21         cur.next=head;//成环
    22         cur=head;
    23         k=l-k;//找头结点
    24         while(--k!=0)
    25         {
    26             cur=cur.next;
    27         }
    28         head=cur.next;
    29         cur.next=null;
    30         return head;
    31     }
    32     
    33 }
    原创供学习参考使用,转载请注明出处http://www.cnblogs.com/cuphoria/ @jm_epiphany
  • 相关阅读:
    Unity 历史版本的安装
    jQuery使用记录
    tkinter 按钮响应函数传值
    python网络爬虫入门(二)
    python 爬取豆瓣书籍信息
    python 爬取猫眼电影top100数据
    SpringMVC+SpringBoot+MyBatis
    时间日期类
    Mybatis框架(三)
    Java框架之MyBatis框架(二)
  • 原文地址:https://www.cnblogs.com/cuphoria/p/10465903.html
Copyright © 2020-2023  润新知