Total Accepted: 55428 Total Submissions: 250727 Difficulty: Medium
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: int getListLength(ListNode* head) { int len = 0; while(head){ len++; head = head->next; } return len; } ListNode* rotateRight(ListNode* head, int k) { int len = getListLength(head); k = len ==0 ? 0 : len - k%len ; if(head ==NULL || k==0 || k==len){ return head; } ListNode *newHead = NULL; ListNode *cur = head; int cnt =0 ; while(cur){ ++cnt; if(cnt == k){ newHead = cur->next; cur->next=NULL; break; } cur = cur->next; } ListNode* p=newHead; while(p && p->next){ p = p->next; } if(p){ p->next=head; } return newHead; } };
Next challenges: (M) Remove Duplicates from Sorted List II (H) Copy List with Random Pointer (M) Reorder List
时间: 2024-10-25 15:02:19