`
cozilla
  • 浏览: 89209 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[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) {
        ListNode* tail = NULL;
        int len = getLen(head, tail);
        if (len <= 0) return head;
        k %= len;
        if (k == 0) return head;
        k = len - k;
        
        ListNode* cur = head;
        while (k-->1) cur = cur->next;
        ListNode* newHead = cur->next;      
        tail->next = head;
        cur->next = NULL;
        return newHead;    
    }
    
    int getLen(ListNode* head, ListNode*& tail) {
        int cnt = 0;
        while (head != NULL) {
            cnt ++;
            tail = head;
            head = head->next;
        }
        return cnt;
    }
};

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics