Leetcode 61

/**
 * 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) { int num = cnt(head); if(num == 0) return head; k = k%num; if(k == 0) return head; int m = num-k; ListNode* move = head; for(int i=0;i < m-1;i++){ move = move->next; } ListNode* reshead = move->next; ListNode* node1 = reshead; while(node1->next != NULL){node1 = node1->next;} move->next = NULL; node1->next = head; return reshead; } int cnt(ListNode* head){ int res = 0; ListNode* temp = head; while(temp != NULL){ res++; temp = temp->next; } return res; } };

猜你喜欢

转载自www.cnblogs.com/cunyusup/p/9760824.html