leetcode 61:Rotate List
2015-11-19 19:47
211 查看
题目:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
思路:
这题可以先确定链表数,然后找到需要截断的结点,将前半部分的最后一个结点next指向NULL,后半部分接到链表的前半部分前面。
注意边界条件:即k有可能大于等于size。
时间复杂度:O(n)
实现如下:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL) return head;
int size = 1;
ListNode *p = head;
while (p->next)
{
size++;
p = p->next;
}
if (size == k) return head;
k %= size;
ListNode *q = head;
for (int i = 0; i < size - k -1; i++) q = q->next;
p->next = head;
ListNode *r = q->next;
q->next = NULL;
head = r;
return head;
}
};
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
思路:
这题可以先确定链表数,然后找到需要截断的结点,将前半部分的最后一个结点next指向NULL,后半部分接到链表的前半部分前面。
注意边界条件:即k有可能大于等于size。
时间复杂度:O(n)
实现如下:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL) return head;
int size = 1;
ListNode *p = head;
while (p->next)
{
size++;
p = p->next;
}
if (size == k) return head;
k %= size;
ListNode *q = head;
for (int i = 0; i < size - k -1; i++) q = q->next;
p->next = head;
ListNode *r = q->next;
q->next = NULL;
head = r;
return head;
}
};
相关文章推荐