在第k个地方翻转链表
题目
在链表第k的位置上翻转链表
例如一个链表:head–>0–>1->2–>3–>4–>5在3位置上翻转链表后head–>3–>4–>5–>0–>1->2
思路
方法:双重指针实现
非常的简单先找到第k的位置;然后把slow指向的指针指向,
下面就看代码实现:
public static void RotateKLink(LNode head,int k){
if(head==null || head.next==null) return;
LNode slow,fast,tmp;
slow=fast=head.next;
int i;
for ( i = 0; i <k && fast!=null ; i++) {
fast=fast.next;
}
if(i<k) return;
//当fast在链表尾时 slow在k+1的位置
while (fast.next!=null){
slow=slow.next;
fast=fast.next;
}
tmp=slow;
slow=slow.next;
tmp.next=null;
fast.next=head.next;
head.next=slow;
}
构造链表:
//构造链表
public static LNode constructList(){
int i=1;
LNode head=new LNode();
head.next=null;
LNode temp=null;
LNode cur=head;
for (; i <7 ; i++) {
temp=new LNode();
temp.data=i;
temp.next=null;
cur.next=temp;
cur=temp;
}
return head;
}
//打印链表
public static void PrintList(LNode head){
for (LNode cur = head.next; cur !=null ; cur=cur.next) {
System.out.print(cur.data+"->");
}
}
测试:
public static void main(String[] args) {
LNode head = constructList();
System.out.print("链表 :");
PrintList(head);
RotateKLink(head,3);
System.out.print("\n翻转后链表 :");
PrintList(head);
}
结果
链表 :1->2->3->4->5->6->
翻转后链表 :4->5->6->1->2->3->