一、问题描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
二、问题分析
使链表最后一个结点指向头结点构成环;
找到被交换到原来的head位置的下标N后,把head指针指向它,并从N-1处断开。
三、算法代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || k == 0){
return head;
}
//求链表长度
int len = 1; //长度初始化为1
ListNode p = head;
while(p.next != null){
len++;
p = p.next;
}
//把链表连成环,注意此时的p指向最后一个结点
p.next = head;
//寻找到是下标N被交换到原来的head位置
int target = 0;
for(int i = 1; i <= len; i++){
if((i + k) % len == 1){
target = i;
break;
}
}
//找到被交换到原来的head位置的下标N后,把head指针指向它,并从N-1处断开
if(target == 1){
p.next = null;
return head;
}else{
ListNode pre = head;
for(int i = 1; i < target ; i++){
pre =head;
head = head.next;
}
pre.next = null;
return head;
}
}
}