LeetCode.61 Rotate List

题目:

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

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

分析1(实测较分析2快,易理解):
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        //给定链表,对调末尾k个节点
        //求出链表长度
        //需要考虑k大于链表长度的情况,例如:输入【1,2】3 输出【2,1】,输入【1,2】 4 输出【1,2】
        int len=listLength(head);
        if(head==null||k<=0)return head;
        
        //考虑k大于链表节点大的情况
        k=k%len;
        
        //链表长度减去k则为前半部分
        ListNode dummy=new ListNode(0);
        ListNode res=dummy;
        dummy.next=head;
        ListNode cur=head,pre=dummy;
        
        for(int i=len-k;i>0;i--){
            pre=pre.next;
            cur=cur.next;
        }
        
        //调换后半部k个节点
        while(cur!=null){
            pre.next=cur.next;
            cur.next=dummy.next;
            dummy.next=cur;
            dummy=dummy.next;
            cur=pre.next;
        }
        
        return res.next;    
    }
    public int listLength(ListNode head){
        ListNode pre=head;
        int count=0;
        while(pre!=null){
            count++;
            pre=pre.next;
        }
        return count;
    }
}
分析2:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        //首先要看k是否大于链表的长度,若是大于长度,则对其求余k%len的位置旋转
        //最后next指向head,形成一个环,之后遍历新的head的前一个节点的next赋值null,最后返回head
        if(head==null||k<0)return head;
        int count=1;
        ListNode cur=head;
        while(cur.next!=null){
            count++;
            cur=cur.next;
        }
        
        //获取右边开始节点的下标
        k=k%count;
        
        //将最后一个节点next指向head,形成环
        cur.next=head;
        
        //接下来遍历节点数
        int num=count-k;
        for(int i=0;i<num;i++){
            cur=cur.next;
        }
        
        head=cur.next;
        //断链
        cur.next=null;
        return head;
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值