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.
思路:
- 将链表尾部和头部连起来,顺便算出链表长度len
- 计算k% len,把尾指针移动到位,然后断开
/**
* 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* tail = head;
ListNode* newhead = head;
int len = 1;
while (tail->next != NULL)
{
tail = tail->next;
++len;
}
tail->next = head;
k %= len;
for (int i = 0; i < len - k; ++i)
{
tail = tail->next;
}
newhead = tail->next;
tail->next = NULL;
return newhead;
}
};

本文介绍了一种链表操作算法——链表右旋转。通过连接链表尾部与头部,并计算链表长度,实现指定位置的旋转操作。适用于面试备考及算法优化实践。
1175

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



