#61旋转链表medium

code1:使用快慢指针法,快指针先走k步,然后两个指针一起走,当快指针走到末尾时,慢指针的下一个位置是新的顺序的头结点,这样就可以旋转链表,

注意边界条件:原链表为空时,直接返回NULL,还有就是当k大于链表长度和k远远大于链表长度时该如何处理,我们需要首先遍历一遍原链表得到链表长度n,然后k对n取余,这样k肯定小于n

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
       if(head==null) return null;
        int n=0;
        ListNode cur=head;
        while(cur!=null){
            n++;
            cur=cur.next;
        }
        k %=n;
        ListNode fast=head,slow=head;
        for(int i=0;i<k;i++)
            if(fast !=null) fast=fast.next;
        if(fast==null)
            return head;
        while(fast.next !=null){
            fast=fast.next;
            slow=slow.next;
         }
        fast.next=head;
        fast=slow.next;
        slow.next=null;
        return fast;
    }
}

code2:一个指针就够了,原理是先遍历整个链表获得链表长度n,然后此时把链表头和尾链接起来,在往后走n - k % n个节点就到达新链表的头结点前一个点,这时断开链表即可

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
      if(head==null )
          return null;
        int n=1;
        ListNode cur=head;
        while(cur.next !=null){
            n++;
            cur=cur.next;
        }
        cur.next=head;
        int m=n-k%n;
        for(int i=0;i<m;i++)
            cur=cur.next;
        ListNode newhead=cur.next;
        cur.next=null;
        return newhead;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值