[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 }

 

posted @ 2019-03-03 15:35  jm_epiphany  阅读(165)  评论(0编辑  收藏  举报