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)  return head;

        //the length of list and tail of the list
        ListNode *p = head;
        int length = 1;
        while(p->next){
            length++;
            p = p->next;
        }
        ListNode *tail = p;

        p = head;
        //构成环形链表
        tail->next = head;
        k = length - k%length;

        while(k-- > 0)
            tail = tail->next;

        p = tail->next;
        tail->next = NULL;
        return p;
    }
};

results matching ""

    No results matching ""