本题要求如下:
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) {
/* find the tail */
ListNode* tail = head;
ListNode* temp = head;
if (head == NULL || head->next == NULL)
return head;
int len = 0;
while (tail != NULL) {
tail = tail->next;
++len;
if (tail->next == NULL) {
++len;
break;
}
}
tail->next = head;
int k_final = len - 1 - k % len;
while (k_final != 0) {
--k_final;
head = head->next;
}
temp = head->next;
head->next = NULL;
return temp;
}
};
基本算法:
1,利用while循环找到该linked list的长度,并把tail指针指向该linkedlist最后一个node
2, 让tail的下一个node是head node
3,最后一步,找到应该断开的点,将其下一个node指向NULL