(链表)20-旋转链表

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 class Solution {
12     public ListNode rotateRight(ListNode head, int k) {
13         // 针对空链表或单节点链表直接返回
14         if (k == 0 || head == null || head.next == null) {
15             return head;
16         }
17         // 初始链表长度
18         int n = 1;
19         // 计算链表长度
20         ListNode iter = head;
21         while (iter.next != null) {
22             iter = iter.next;
23             n++;
24         }
25         // 计算头结点平移长度
26         int add = n - k % n;
27         if (add == n) {
28             return head;
29         }
30         // 将链表头尾连接成环
31         iter.next = head;
32         // 找到新的尾节点
33         while (add > 0) {
34             iter = iter.next;
35             add --;
36         }
37         // 找到新的头节点
38         ListNode result = iter.next;
39         // 头尾断开
40         iter.next = null;
41         // 返回结果
42         return result;
43     }
44 }

 

posted @ 2023-11-20 22:41  StringBuilder  阅读(2)  评论(0编辑  收藏  举报