1 问题
链表 1-> 2-> 3-> 4-> 5-> 6-> 7 。K=3 那么旋转后链表为 5-> 6-> 7-> 1-> 2-> 3-> 4
2 问题分析
1)首先找到倒数第K+1个节点 slow为尾结点fast.(定义两个快慢指针,先让fast走K步,然后在同时走。)
2)把链表断开成两个子链表,其中后半部分链表节点的个数为K个。
3)让原链表的结尾指向链表的第一个节点
4)让链表的头结点指向链表的倒数第K个节点。
3 代码实现
package RotateLinkedList;
public class RotateLinkedList {
public static void main(String[] args) {
LNode head = ConstructList();
System.out.println("没有旋转前:");
print(head);
RotateK(head,3);
System.out.println("旋转后:");
print(head);
}
//构建一个链表
public static LNode ConstructList(){
int i=1;
LNode head=new LNode();
head.next=null;
LNode tmp=null;
LNode cur=head;
for (;i<8;i++){
tmp=new LNode();
tmp.date=i;
tmp.next=null;
cur.next=tmp;
cur=tmp;
}
return head;
}
//遍历链表
public static void print(LNode head){
LNode cur=null;
for (cur=head.next;cur!=null;cur=cur.next){
System.out.print(cur.date+"-> ");
}
}
//把链表有旋转
public static void RotateK(LNode head,int k){
if (head==null||head.next==null){
return ;
}
//fast指针先走K步,之后与slow在同时走
LNode fast,slow,tmp;
fast=slow=head.next;
int i=0;
for (;i<k && fast!=null;++i){//i先移动,同时要保证fast不能超出链表的长度
fast=fast.next;
}
if (i<k){//判断K 是否大于长度
return;
}
while (fast.next!=null){
fast=fast.next;
slow=slow.next;
}
tmp=slow;//这时 tmp指向倒数第K+1的节点
slow=slow.next;//slow后移一位
tmp.next=null;//将倒数第K+1的节点 变成尾结点
fast.next=head.next;//将原来的链表尾结点变成指向原来的第一个节点
head.next=slow;//head指向slow
}
}
class LNode{
LNode next;
int date;
}