Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
题目不难,但边界问题容易忽略。下面是自己的解法:
解法思路:简单分析可知,移动k次,当k>L(链表长度时)取n=k%L,将整个链表分为长度为L-n的前部分,和长度为n的后段部分,将前后调换即得到旋转后的结果。
/**
* 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) {
ListNode* preHead=new ListNode(0);//哑结点
preHead->next=head;
int l=0;
ListNode* p=head;
while(p)
{
p=p->next;
l++;
}//链表长度
if(l==0) return head;//处理边界问题1,空链表
int n=k%l,x=0;
p=preHead;
while(x<l-n)
{
p=p->next;
x++;
}//此时p指向前半段的最后一个结点,也就是旋转后链表的尾结点
preHead->next=p->next;
p->next=nullptr;
p=preHead->next;//p指向后半段的第一个结点
if(p==nullptr) return head;//处理边界问题2,链表旋转后不变,即l-n=0
while(p->next)
{
p=p->next;
}//遍历到链表尾部,将尾部的next指向head。
p->next=head;
return preHead->next;
}
};
边界问题一报错
边界问题二报错
后半段为空,p=preHead->next; //p指向后半段的第一个结点
此句执行后p为空,下一句while(p->next)会报错。
代码写之前还是的提前考虑边界条件
if(k == len || k%len == 0)
return head;
这样就简单粗暴多了