题目: 给定一个链表,将链表向右轮换k个位置(k>=0)
例如:1->2->3->4->5 k=2, 则轮换后链表为:4->5->1->2->3
1->2->3 k=4,则轮换后链表为:3->1->2难度:Medium
思路:定义两个指针,fast用来统计链表的长度count;slow指针用来查找开始旋转的位置;如果k>count,则k需要取余; 链表需要移动的长度为(count -1 - k%count)
代码:
/**
* 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 || head.next == null || k == 0){
return head;
}
ListNode fast = head;
ListNode slow = head;
ListNode node = null;
ListNode newHead = new ListNode(0);
int count = 0;//统计链表长度
while(fast != null ){
count++;
node = fast;
fast = fast.next;
}
k =k%count;//对k取余
if(k == 0){
return head;
}
while(count -1 - k > 0){
slow = slow.next;
k++;
}
newHead.next = slow.next;
node.next = head;
slow.next = null;
return newHead.next;
}
}
- 来自Discuss里的方法(思路与我的一样,但是代码更简洁)
public ListNode rotateRight(ListNode head, int n) {
if (head==null||head.next==null) return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode fast=dummy,slow=dummy;
int i;
for (i=0;fast.next!=null;i++)//Get the total length
fast=fast.next;
for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
slow=slow.next;
fast.next=dummy.next; //Do the rotation
dummy.next=slow.next;
slow.next=null;
return dummy.next;
}
给链表加上一个没有具体意义的“头结点”可以省去很多判断空指针的情况
对于链表类的题目,一般定义两个指针即可