Leetcode rotate list

来源:互联网 发布:java测试工程师累吗 编辑:程序博客网 时间:2024/05/16 04:28
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode * newhead = NULL;
        ListNode * pre=NULL;
        ListNode * temp = head;

        int i=0;
        int length=0;
        
        if(head == NULL)
        return NULL;
        
        //find length
        while(temp!=NULL)
        {
            length++;
            temp=temp->next;
        }        
        k=k%length;
        
        if (k==0)
        return head;        
        temp=head;
        
        for(i=0; i<length-k;i++)
        {
            pre=temp;
            temp=temp->next;
        }
        pre->next=NULL;
        newhead=temp;
        while(temp->next!=NULL)
        {
            temp=temp->next;
        }
        temp->next=head;
            
        return newhead;
    }
};
原创粉丝点击