LeetCode_rotate-list

题目描述:

Given a list, rotate the list to the right by kplaces, where k is non-negative.

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

这个意思有点表达不清,翻译过来就是从倒数第k个节点开始,反转过来

思路:注意到这里的测试样例里k是有可能会大于这个链表的长度的,所以我们应该

                  1.先遍历一边求出这个链表的长度

                  2.要求倒数第k个节点,那么拿的前一个节点就是n-k节点(这里我们先在求链表长度的之后把这个链表绕成一个环)

                  3.找到n-k节点,断开就可以了

注释部分那个方法也是可以用的,不过不简练;

    public ListNode rotateRight(ListNode head, int n) {
        if(head==null||head.next==null||n==0)
            return head;
        int len=1;
        ListNode cur=head;
        while(cur.next!=null){
            len++;
            cur=cur.next;
        }
        //倒数第k节点 那么这个几点的前一个节点就是顺数 len-k个节点
        n=len-n%len;//flag1
        //先把这个链成环
        cur.next=head;
        //此时cur指向的还是head的上一个节点,我们要移动到第n(flag1处理后)个节点 则需要移动 n次;
        for(int i=0;i<n;i++){
            cur=cur.next;
        }
        ListNode nHead=cur.next;
        cur.next=null;
        return nHead;
    }
    /*
    public ListNode rotateRight(ListNode head, int n) {
        if(head==null||head.next==null||n==0)
            return head;
        int len=0;
        ListNode cur=head;
        while(cur!=null){
            len++;
            cur=cur.next;
        }
        n%=len;
        if(n==0)
            return head;
        ListNode pre=head;
        ListNode last=head;
        for(int i=0;i<n;i++){
            if(pre!=null)
                pre=pre.next;
        }
        while(pre.next!=null){
            pre=pre.next;
            last=last.next;
        }
        ListNode nHead=last.next;
        last.next=null;
        pre.next=head;
        return nHead;
    }*/

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值