在第k个地方翻转链表

在第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->

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值