@TOC
题目描述
解题思路
- 遍历链表,找到尾结点(同时获得链表长度length),并将尾结点的next指向头结点,形成一个循环单链表。
- 从第length - k个节点开始返回(需要断开第length-k-1个节点,使其next指针指向null)
代码实现
/**
* 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 || k == 0) return head;
ListNode temp = head;
int length = 0; //记录链表长度
while(temp.next != null){
++length;
temp = temp.next; //找到尾结点
}
++length;
temp.next = head; //尾结点指向头结点,形成循环链表
k = k % length;
ListNode front = head;
for(int i=1;i<=length-k;i++){
head = head.next; //找到第length-k个节点
}
for(int i=1;i<=length-k-1;i++){
front = front.next; //找到第length-k-1个节点
}
front.next = null; //断开第length-k个节点与第length-k-1个节点
return head; //返回第length-k个节点
}
}