题目:
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
代码:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL || head->next == NULL || k == 0)
{
return head;
}
else{
ListNode *p = head; //用来遍历的指针
ListNode *tail = NULL; //尾节点
ListNode *newhead = NULL; //新的头指针
ListNode *newtail = NULL; //新的尾节点
int len = 0; //链表长度
//第一步计算链表的长度
while (p->next != NULL)
{
len++;
p = p->next;
}
tail = p;
len++;
//第二部,计算需要翻转的节点数num,同时进行翻转
int num = k % len;
if (num == 0 || num == len)
{
return head;
}
else
{
newtail = head;
int count = 1;
while (count < (len - num ))
{
newtail = newtail->next;
count++;
}
newhead = newtail->next;
tail->next = head;
newtail->next = NULL;
return newhead;
}
}
}
};
结果:
思路:
- 刚开始把题目意思理解错了,以为k代表的是链表下标,然后发现多次提交之后,给出的例子貌似有冲突。于是百度了一下该题正确的意思,发现是旋转k的节点。然后思路就很清晰了