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
.
题意:给定一个链表和一个k值,将链表向右旋转K个位置
/**
* 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) return null;
//链表有一个元素或者k值为0 ,返回该链表
if(head.next == null || k == 0) return head;
ListNode dummy = new ListNode(0);
ListNode curNode = head;
//声明length记录链表长度,while循环遍历链表,求出长度
int length = 1;
while(curNode.next != null){
length++;
curNode = curNode.next;
}
//如果k值和链表长度相等,等于不用反转,直接返回原链表
if (k % length == 0) {
return head;
}
/* 因为k可能比length长,所以用k%length求出旋转的位置
1->2->3->4->5->null;如果k=3,那么设置原链表的第2个节
点指向null;即第2个节点是新表的尾节点。
尾节点 = length-k%length;
*/
//减1是为了下面的while循环,curNode取到length-k%length的位置上
int num =length - k % length -1;
//curNode重新指向表头,向后遍历,取到length-k%length的位置上
curNode = head;
while(num > 0){
curNode = curNode.next;
num--;
}
//记录curNode后面的节点,即新链表的头结点
ListNode nextNode = curNode.next;
//将新表的尾节点指向null
curNode.next = null;
//用dummy.next指向新链表的表头
dummy.next = nextNode;
//遍历到新链表的尾节点
while(nextNode.next != null){
nextNode = nextNode.next;
}
//使尾节点指向就链的头结点
nextNode.next = head;
return dummy.next;
}
}