码迷,mamicode.com
首页 > 其他好文 > 详细

[Linked List]Rotate List

时间:2015-12-12 17:11:45      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

[Linked List]Rotate List

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5041441.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!