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 || head->next == NULL)
return head;
if (k <= 0) return head;
int len = 0;
ListNode *p = head, *tail = head;
while (p) {
len++;
tail = p;
p = p->next;
}
k = k % len;
if (k == 0) return head;
int i = 0;
p = head;
while (p) {
i++;
if (i == len - k)
break;
p = p->next;
}
ListNode *tmp_head = p->next;
p->next = NULL;
tail->next = head;
return tmp_head;
}
};

本文介绍了一种链表向右循环移位k次的算法实现。通过计算链表长度并利用尾节点连接头节点的方式形成闭环,再通过断开指定位置节点完成循环移位,最终返回新的链表头部。
1169

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



