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 == NULL) {
return head;
}
ListNode* newHead = head;
ListNode* cur = head;
ListNode* last;
int n = 0;
while(cur != NULL) {
last = cur;
cur = cur->next;
++n;
}
k = k % n;
if (k == 0) {
return head;
}
ListNode* pre;
for (int i = n; i > k; --i) {
pre = newHead;
newHead = newHead->next;
}
pre->next = NULL;
last->next = head;
return newHead;
}
};
本文介绍了一种链表右旋转算法的实现方法,通过调整链表节点指针,将链表向右旋转k个位置。文章详细展示了如何通过一次遍历获取链表长度,并根据k值调整链表结构。
203

被折叠的 条评论
为什么被折叠?



