旋转链表

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
// 链表长度
int length = getLength(head);
// 取余
k = k % length;
// 算出头节点右移多少之后得到新的头节点
k = length - k;
// 尾节点,后面需要连到旧头节点
ListNode tail = getTail(head);
ListNode temp = head;
while (k > 1) {
temp = temp.next;
k--;
}
// 此时,temp.next是新的头节点
// 旧尾节点连到旧头节点
tail.next = head;
// 新头节点
head = temp.next;
// temp是新头节点的上一个节点,断开与新头结点的链接
temp.next = null;
return head;
}
private ListNode getTail(ListNode head) {
while (head != null) {
if (head.next == null) {
break;
}
head = head.next;
}
return head;
}
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
}
积跬步以致千里,积小流以成江海。
2016年5月之前的博文发布于51cto,链接地址:shamrock.blog.51cto.com
2016年5月之后博文发布与cnblogs上。
Github地址 https://github.com/umgsai
Keep moving~!!!
2016年5月之前的博文发布于51cto,链接地址:shamrock.blog.51cto.com
2016年5月之后博文发布与cnblogs上。
Github地址 https://github.com/umgsai
Keep moving~!!!

浙公网安备 33010602011771号