1、61. 旋转链表
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
思路:
先遍历一遍,得出链表长度len,注意k可能会大于len,因此k%=len。
将尾结点next指针指向首节点,形成一个环,接着往后跑len-k步,从这里断开,就是结果
public ListNode rotateRight(ListNode head, int n) {
if (head == null)
return null;
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode cur = head;
int length = 1;
//目的是让cur指向最后一个节点;计算length
while (cur.next != null) {
length++;
cur = cur.next;
}
n = n % length;
if (n == 0)
return head;
//首位相连
cur.next=head;
//这不对 例子1->2 k=1,要换成下面的代码
// cur=head;
// while (n-->0){
// cur=cur.next;
// }
for (int i=0;i<length-n;i++){
cur=cur.next;
}
head=cur.next;
cur.next=null;
return head;
}