61. 链表右移

题目链接:

https://leetcode-cn.com/problems/rotate-list/comments/

 

解题思路:

 

先弄成环,然后断链接。

 1 class Solution {
 2     public ListNode rotateRight(ListNode head, int k) {
 3         if(head == null) return null;
 4         ListNode cur = head;
 5         int n = 1;
 6         while(cur.next != null){//得到链表的长度
 7             n++;
 8             cur = cur.next;
 9         }
10         cur.next = head;//行成循环链表
11         int m = n - k % n;
12         for(int i = 0; i < m; i++){//到达新链表头节点的前一个节点
13             cur = cur.next;
14         }
15         ListNode newHead = cur.next;
16         cur.next = null;
17         return newHead;
18     }
19 }

 

posted @ 2019-07-25 17:00  王爷爱吃秋刀鱼  阅读(307)  评论(0编辑  收藏  举报