当前位置:编程学习 > C/C++ >>

[leetcode]Rotate List

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!head) return NULL;
        
        int N = 0;
        ListNode *end = head;
        while(end->next){
            end = end->next;
            N++;
        }
        N++;
        
        k = k%N;
        if(k == 0) return head;
        
        int M = N - k;
        
        ListNode* p = head;
        for(int i = 0; i < M-1; i++){
            p = p->next;
        }
        
        ListNode *q = p->next;
        p->next = NULL;
        end->next = head;
        return q;
        
    }
};

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,