题目如下:
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
.
解题思路:
会有以下几种情况
(1) 链表为空或者链表只有一个元素,直接返回原链表
(2)当k等于链表长度,相当于不用右移;当k大于链表长度,相当于只要右移k%(链表长度)个位置
根据给定的例子说明如何右移:
我们找到倒数第k+1个位置,用两个指针同时遍历;倒数第k+1个位置即为3,则它的后面的元素需要被插入到头结点的位置。(这里设置一个Head指针作为哨兵,用来简化头插操作。)同时原链表最后一个元素即为5的next指针应该指向head。最后返回Head.next即可。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head == null || head.next == null) return head;//情况一
int length = 0;
ListNode p = head;
while(p != null){
length++;
p = p.next;
}
int times = n % length; //times表示右移的个数
if(times == 0) return head; //如果右移个数为0,则不作处理,否则做如下处理
ListNode Head = new ListNode(-1);
Head.next = head;
ListNode after = head;
ListNode before = Head;
for(int i = 0; i < times + 1; i++){
before = before.next;
}
while(before.next != null){
after = after.next;
before = before.next;
}
ListNode split = after.next;
after.next = null;
Head.next = split;
before.next = head;
return Head.next;
}
}