LeetCode OJ:Rotate List

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.


算法思想:

len表示链表长度,将链表变成循环链表,在len-k%len处将链表一分为二

/**
 * 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)return NULL;

        ListNode *p=head,*q=head,*prep=NULL,*preq=NULL;
        int len=0;
        while(p){
            len++;
            prep=p;
            p=p->next;
        }
        prep->next=head;
        k=len-k%len;
        while(k--){
            preq=q;
            q=q->next;
        }
        
        preq->next=NULL;
        return q;
    }
};


你可能感兴趣的:(LeetCode)