您的位置:首页 > 其它

【Leetcode】【Medium】Rotate List

2015-05-19 03:10 162 查看
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
.

解题思路:

题目看上去很简单,但是需要注意一下点:

1、任何输入都有可能,即使是无效的输入(例如链表为空,k不为0),所以程序开始时的检查在任何时候都非常重要。

2、另一个边界条件,就是是否在空指针中,使用了->next操作,很多链表错误都发生在此处。

3、K是旋转的结点数,因此K可能大于整个链表的结点数。

4、K不仅可能大于结点数,还可能非常大,因此传统的循环耗费时间太多,要对K做取余操作。

代码:

/**
* 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 (k == 0 || !head)
return head;
ListNode* pre = head;
ListNode* last = head;
int num = 1;
while (k--) {
if (last->next) {
num++;
last = last->next;
} else {
k = k % num;
last = head;
}
}

while (last->next) {
pre = pre->next;
last = last->next;
}

last->next = head;
head = pre->next;
pre->next = NULL;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: