Rotate List问题及解法
2017-07-29 08:34
330 查看
问题描述:
Given a list, rotate the list to the right by k places, where k is non-negative.
示例:
Given
return
问题分析:
根据题意,先求出总的节点个数num,再确定需要旋转后移的个数r = num - 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) {
int num = 0;
ListNode* head2 = head;
ListNode* tail;
while (head2)
{
num++;
tail = head2;
head2 = head2->next;
}
if (!num || k % num == 0) return head;
int r = num - k % num;
while (r--)
{
tail->next = head;
head = head->next;
tail->next->next = NULL;
tail = tail->next;
}
return head;
}
};
Given a list, rotate the list to the right by k places, where k is non-negative.
示例:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
问题分析:
根据题意,先求出总的节点个数num,再确定需要旋转后移的个数r = num - 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) {
int num = 0;
ListNode* head2 = head;
ListNode* tail;
while (head2)
{
num++;
tail = head2;
head2 = head2->next;
}
if (!num || k % num == 0) return head;
int r = num - k % num;
while (r--)
{
tail->next = head;
head = head->next;
tail->next->next = NULL;
tail = tail->next;
}
return head;
}
};
相关文章推荐
- Remove Nth Node From End of List问题及解法
- Rotate Array问题及解法
- Delete Node in a Linked List问题及解法
- Convert Sorted List to Binary Search Tree问题及解法
- 【LeetCode】61. Rotate List解法及分析
- Split Linked List in Parts问题及解法
- Linked List Cycle II问题及解法
- Rotate String 问题使用取余解法
- Linked List Random Node问题及解法
- Insertion Sort List问题及解法
- Remove Duplicates from Sorted List问题及解法
- Flatten Binary Tree to Linked List问题及解法
- Odd Even Linked List问题及解法
- Copy List with Random Pointer问题及解法
- Reorder List问题及解法
- Rotate Image问题及解法
- Remove Duplicates from Sorted List II问题及解法
- Rotate Function问题及解法
- Reverse Linked List II问题及解法
- LeetCode Rotate List简单易懂解法