题目所属分类
旋转链表
原题链接
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
代码案例:
题解
/**
* 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) return head ;
int n = 0 ;
ListNode tail = head ;
for(ListNode p = head ; p != null ; p = p.next){
tail = p ;
n++ ;
}
k %= n ;
if(k == 0) return head ;
ListNode p = head ;
for(int i = 0 ; i < n - k - 1; i++) p=p.next;
tail.next = head ;
head = p.next ;
p.next = null ;
return head ;
}
}