给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode* Init(ListNode* head)
{
int val = 0;
ListNode* p = NULL;
while (true)
{
cin >> val;
if (-1 == val)
{
return head;
}
if (NULL == head)
{
head = new ListNode(val);
p = head;
}
else
{
p->next = new ListNode(val);
p = p->next;
}
}
}
int getListLength(ListNode* head)
{
int count = 0;
if (NULL == head)
{
return 0;
}
else
{
ListNode* p = head;
while (p!=NULL)
{
count++;
p = p->next;
}
}
return count;
}
ListNode *rotateRight(ListNode *head, int k) {
// write your code here
int len = getListLength(head);
if (0 == len || NULL == head)
{
return 0;
}
k = k%len;
if (k == len || 0 == k)//反转的次数和长度一样或者反转的长度为0,直接返回
{
return head;
}
ListNode* tail = NULL;
ListNode* prev = head;
ListNode* p = head;
int count = len - k;
count--;//因为这个链表没有头结点,头就是第一个节点,所以要先减一
while (count--)
{
p = p->next;
}
tail = p->next;
p->next = NULL;
p = tail;
while (p->next!=NULL)
{
p = p->next;
}
p->next = prev;
return tail;
}
void Out(ListNode* head)
{
if (head !=NULL)
{
ListNode* p = head;
while (p)
{
cout << p->val << " ";
p = p->next;
}
}
cout << endl;
}
};
int main()
{
ListNode* head = NULL;
Solution s;
head = s.Init(head);
s.Out(head);
int k = 0;
cin >> k;
head = s.rotateRight(head, k);
s.Out(head);
return 0;
}