版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012503241/article/details/82915043
题目:Given a linked list, rotate the list to the right by k places, where k is non-negative.
解题思路:所谓链表循环右移就是头插法,但是这个题你要是一个一个得去做会导致超时,所以我们把需要移动的节点看成是一起的,以start开始,tail结束。
代码:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode rotateRight(ListNode head, int k) {
if(head == null)return null;
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
ListNode start = head;
ListNode tail = head;
int len = 1;
while (tail.next!=null){
len++;
tail = tail.next;
}
k = k%len;
if(k == 0)return head;
for (int i = 0;i<len-k;i++){
pre = pre.next;
start = start.next;
}
pre.next = tail.next;
tail.next = dummyNode.next;
dummyNode.next = start;
return dummyNode.next;
}