leetcode[61]Rotate List

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:

ListNode *rotateRight(ListNode *head, int k) 

{

    if(head==NULL||head->next==NULL||k==0)

        return head;

    ListNode *pre0=head ,*pre1, *pre2;

    int len=0;

    while (pre0)

    {

        len++;

        pre1=pre0;

        pre0=pre0->next;

    }

    k%=len;

    if(k==0)return head;

    ListNode  *headNew;

    pre2=head;

    for(int i=0;i<len-k-1;i++)

    {

        pre2=pre2->next;

    }

    headNew=pre2->next;

    pre2->next=NULL;

    pre1->next=head;

    return headNew;

}

/**

ListNode *rotateRight(ListNode *head, int k) 

{

    if(head==NULL||head->next==NULL||k==0)

        return head;

    ListNode *pre0=head;

    int len=0;

    while (pre0)

    {

        len++;

        pre0=pre0->next;

    }

    k%=len;

    if(k==0)return head;

    ListNode *pre1=head, *cur, *headNew;

    int icount=0;

    while(pre1)

    {

        icount++;

        pre1=pre1->next;

        if (icount==k)

        {        

            cur=head;

            while(pre1->next)

            {

                pre1=pre1->next;

                cur=cur->next;

            }

            headNew=cur->next;            

            cur->next=NULL;

            pre1->next=head;    

            return headNew;

        }

    }

}

*/

};

 

你可能感兴趣的:(LeetCode)