61. 旋转链表


 

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

 

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

题解:
自己的思路:

  1. 当k=0或链表为空或链表只有一个元素时直接return head
  2. 计算出链表的总长度lengthOfHead,并用k%lengthOfHead求出实际该旋转的个数
  3. 利用快慢指针first和second找出旧链表末尾元素和新链表的首元素
  4. 将指向末尾的指针first指向head,并使second.next=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         ListNode tmp = head;
12         ListNode first = head;
13         ListNode second = head;
14         if (k == 0 || head == null || head.next == null) {
15             return head;
16         }
17         int lengthOfHead = 0;
18         while (tmp != null) {
19             tmp = tmp.next;
20             lengthOfHead++;
21         }
22         k = k % lengthOfHead;
23         for (int i=0; i<k; i++) {
24             first = first.next;
25         }
26         while (first.next != null) {
27             first = first.next;
28             second = second.next;
29         }
30         first.next = head;
31         tmp = second.next;
32         second.next = null;
33         return tmp;
34     }
35 }

 

posted @ 2020-11-10 13:36  Vingkin  阅读(106)  评论(0)    收藏  举报