[Linked List]Rotate List

Total Accepted: 55428 Total Submissions: 250727 Difficulty: Medium

 

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getListLength(ListNode* head)
    {
        int len = 0;
        while(head){
            len++;
            head = head->next;
        }
        return len;
    }
    ListNode* rotateRight(ListNode* head, int k) {
        int len = getListLength(head);
        k = len ==0 ?  0 : len - k%len ;
        if(head ==NULL || k==0 || k==len){
            return head;
        }
        ListNode *newHead = NULL;
        ListNode *cur     = head;
        int cnt =0 ;
        while(cur){
            ++cnt;
            if(cnt == k){
                newHead = cur->next;
                cur->next=NULL;
                break;
            }
            cur = cur->next;
        }
        ListNode* p=newHead;
        while(p && p->next){
            p = p->next;
        }
        if(p){
            p->next=head;  
        } 
        return newHead;
    }
};
posted @ 2015-12-12 16:36  zengzy  阅读(177)  评论(0编辑  收藏  举报
levels of contents