【题目】
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个结点。
不是很难,主要是几个易错点:1)k 可能大于等于链表长度!!!2)链表为空或长度为1。
/**
* 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 || n < 1) return head;
//遍历链表求其长度,并找到尾部
ListNode node = head;
ListNode tail = null;
ListNode newhead = null;
int len = 0;
while (node != null) {
len++;
tail = node;
node = node.next;
}
//只有一个结点时,返回原链表即可
if (len == 1 || n % len == 0) return head;
//把链表首位拼接
tail.next = head;
//找到右移后的链表尾部
node = head;
int i = 1;
while (i != len - n % len) {
i++;
node = node.next;
}
newhead = node.next;
node.next = null;
return newhead;
}
}