链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List

  • 题目: 给定一个链表,将链表向右轮换k个位置(k>=0)
    例如:1->2->3->4->5 k=2, 则轮换后链表为:4->5->1->2->3
    1->2->3 k=4,则轮换后链表为:3->1->2

  • 难度:Medium

  • 思路:定义两个指针,fast用来统计链表的长度count;slow指针用来查找开始旋转的位置;如果k>count,则k需要取余; 链表需要移动的长度为(count -1 - k%count)

  • 代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null || k == 0){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        ListNode node = null;
        ListNode newHead = new ListNode(0);
        int count = 0;//统计链表长度
        while(fast != null ){
            count++;
            node = fast;
            fast = fast.next;
        }

       k =k%count;//对k取余
       if(k == 0){
           return head;
       }
        while(count -1 - k > 0){
            slow = slow.next;
            k++;
        }
         newHead.next = slow.next;
         node.next = head;
         slow.next = null;
         return newHead.next;

    }
}
  • 来自Discuss里的方法(思路与我的一样,但是代码更简洁)
public ListNode rotateRight(ListNode head, int n) {
    if (head==null||head.next==null) return head;
    ListNode dummy=new ListNode(0);
    dummy.next=head;
    ListNode fast=dummy,slow=dummy;

    int i;
    for (i=0;fast.next!=null;i++)//Get the total length 
        fast=fast.next;

    for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
        slow=slow.next;

    fast.next=dummy.next; //Do the rotation
    dummy.next=slow.next;
    slow.next=null;

    return dummy.next;
}

给链表加上一个没有具体意义的“头结点”可以省去很多判断空指针的情况

对于链表类的题目,一般定义两个指针即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值