4.29 leetcode -29 rotate-list
2017-08-31 14:43
330 查看
题目描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
这个问题,我同学和我说,面试出过问题。
需要小心的点是,k > 链表长度,此时相当于又一个mod过程。
思路不难,两个指针,前后走就行。
/**
* 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 *pToEnd = head;
ListNode *pNewEnd = head;
ListNode *pNewHead;
if(head == NULL)
return NULL;
int i = 0;
for(; i < k ;i ++)
{
if(pToEnd->next == NULL)//k大于链表长度的话
pToEnd = head;
else
pToEnd = pToEnd->next;
}
while(pToEnd->next != NULL)
{
pToEnd = pToEnd->next;
pNewEnd = pNewEnd->next;
}
pToEnd->next = head;
pNewHead = pNewEnd->next;
pNewEnd->next = NULL;
return pNewHead;
}
};
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
这个问题,我同学和我说,面试出过问题。
需要小心的点是,k > 链表长度,此时相当于又一个mod过程。
思路不难,两个指针,前后走就行。
/**
* 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 *pToEnd = head;
ListNode *pNewEnd = head;
ListNode *pNewHead;
if(head == NULL)
return NULL;
int i = 0;
for(; i < k ;i ++)
{
if(pToEnd->next == NULL)//k大于链表长度的话
pToEnd = head;
else
pToEnd = pToEnd->next;
}
while(pToEnd->next != NULL)
{
pToEnd = pToEnd->next;
pNewEnd = pNewEnd->next;
}
pToEnd->next = head;
pNewHead = pNewEnd->next;
pNewEnd->next = NULL;
return pNewHead;
}
};
相关文章推荐
- 29_leetcode_Rotate List
- [LeetCode] 092: Rotate List
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- [LeetCode] 61. Rotate List
- Leetcode: Rotate List
- LeetCode Rotate List
- LeetCode_61---Rotate List
- [LeetCode] Rotate List
- [Leetcode]61. Rotate List
- Leetcode 61. Rotate List (Medium) (cpp)
- LeetCode:Rotate List
- Leetcode -- Rotate List
- [Leetcode]61. Rotate List @python
- C++ STL@ list 应用 (leetcode: Rotate Array)
- 【一天一道LeetCode】#61. Rotate List
- LeetCode Rotate List (链表操作)
- leetcode之Rotate List
- Leetcode 61. Rotate List (旋转链表)
- [leetcode笔记] Rotate List
- leetcode---Rotate List---链表