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.
Subscribe to see which companies asked this question
含义:向右旋转单链表
思路:用一个辅助root结点连接到链表头,先找到要移动的第一个结点的前驱prev,再将prev后的所有结点接到root后面,再将组成一个旋转后的单链表。
(k的取值,注意为负数或者超出链表长度)
head.next------指向1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length ++;
head = head.next;
}
return length;
}
public ListNode rotateRight(ListNode head, int n) {
if(n<=0||head==null){return head;}
int length = getLength(head);
n = n % length;
ListNode dump=new ListNode(0);
dump.next=head;
ListNode pre=dump;
ListNode tail=dump;
for(int i=0;i<length-n;i++){
pre=pre.next;//需要反转元素的前一个元素
tail=tail.next;
}
while(tail.next!=null){ tail=tail.next;}//末尾元素
tail.next=dump.next;
dump.next=pre.next;
pre.next=null;
return dump.next;
}
}
方案二:
让一个节点先跑n,然后和另一个节点头一起走,就会遇到倒数第k个节点。

257

被折叠的 条评论
为什么被折叠?



