论坛首页 入门技术论坛

[LeetCode] Rotate List

浏览 1089 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-12  

 

 

 

/**
 * 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