[leetcode] 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.

陷阱挺多,需要小心。

1. 如果链表为空或k==0,return head;

2. 如果k>链表长度count, k = k % count;

/**
 * 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 || k == 0) return head;
        int count = 0;
        ListNode * p = head;
        ListNode * tail;
        while(p != NULL){
            tail = p;
            p = p->next;
            count++;
        }
        k = k % count;
        p = head;
        while(count - k  - 1 > 0){
            p = p->next;
            count--;
        }
        tail->next = head;
        head = p->next;
        p->next = NULL;
        return head;
        
    }
};

 

 

 

Selection_034

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.