前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 61. Rotate List

LeetCode 61. Rotate List

作者头像
ShenduCC
发布2019-09-16 10:14:43
4870
发布2019-09-16 10:14:43
举报
文章被收录于专栏:算法修养算法修养

题目

c++

代码语言:javascript
复制
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {

        if(head==NULL)
            return head;
        if(k==0)
            return head;
        ListNode* end ;
        ListNode* start = head;
        ListNode* pre;
        ListNode* term =head;
        
        int len=1;
        
        while(head->next!=NULL)
        {
            head = head->next;
            len++;
        }
        
        if(len==1)
            return head;
        
        end = head;
        
        int n = k%len;
        
        if(n==0)
            return start;
        
        int m = len-n;
        
        head = start;
        int i=0;
        while(head!=NULL)
        {
            if(i==m)
            {
                start = head;
                break;
            }
            if(i==m-1)
            {
                pre=head;
            }
            
            i++;
            
            head=head->next;
        }
        
        pre->next=NULL;
        end->next=term;
        
       
        
        return start;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档