Rotate List LeetCode 题解

首先上题目:
在这里插入图片描述
题目中给定了一个K(旋转次数),输入一个链表,要求将链表从末尾旋转k次。那么难点在于:

  1. 怎样快速找到链表的末尾
  2. 怎样调整头指针
    对于第二个问题,只需给定一个临时的指针变量,待指到最后一个节点时,将最后一个节点反指回头结点,再将头结点指到临时指针的位置。
    对于第一个问题,可以考虑连续两次移动指针的方式来找到表尾的方式。
    (如下图)
    在这里插入图片描述
    最后,一个非常狗血的问题:测试样例有k值上万的情况。注意到旋转的次数超过链表的长度会出现循环。所以可以对K求余来实现。
    代码:
  int length(ListNode* a)
{
	int fin = 0;
	for (ListNode* temp = a; temp; temp = temp->next)
	{
		fin++;
	}
	return fin;
}
    ListNode* findthelast(ListNode* head, ListNode* tar)
    {
        for(ListNode* temp=head;temp;temp=temp->next->next)
        {
            if(temp->next==tar)
                return temp;
            else if(temp->next->next==tar)
                return temp->next;
        }
        return head;
    }
    ListNode* rotateRight(ListNode* head, int k) {
        if(head&&head->next)
        {
            ListNode* last;
            int sizes = length(head);
            for(int i=0;i<k%sizes;i++)
            {
                last=findthelast(head,NULL);
                ListNode* pre=findthelast(head,last);
                pre->next=last->next;
                last->next=head;
                head=last;
            }
            return head;
        }
        else
          return head;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值