[leetcode #25]Reverse Nodes in k-Group
2015-03-11 16:13
477 查看
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
For k = 2, you should return:
For k = 3, you should return:
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *psave= head;
ListNode *first = head;
ListNode *end = head;
ListNode *temp = NULL;
ListNode *lastfirst = head;
while(1)
{
for(int i=0;i<k-1 && NULL != end;i++)
{
end = end->next;
}
if(end == NULL) {break;}
while(first != end)
{
temp = first->next;
first->next = end->next;
end->next = first;
first = temp;
}
if(head == lastfirst) head = first;
else psave->next = first;
psave = lastfirst;
first = end = lastfirst = lastfirst->next;
}
return head;
}
};
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
1->2->3->4->5
For k = 2, you should return:
2->1->4->3->5
For k = 3, you should return:
3->2->1->4->5
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *psave= head;
ListNode *first = head;
ListNode *end = head;
ListNode *temp = NULL;
ListNode *lastfirst = head;
while(1)
{
for(int i=0;i<k-1 && NULL != end;i++)
{
end = end->next;
}
if(end == NULL) {break;}
while(first != end)
{
temp = first->next;
first->next = end->next;
end->next = first;
first = temp;
}
if(head == lastfirst) head = first;
else psave->next = first;
psave = lastfirst;
first = end = lastfirst = lastfirst->next;
}
return head;
}
};
相关文章推荐
- leetcode (25) - Reverse Nodes in k-Group
- LeetCode(25)Reverse Nodes in K-Group
- [leetcode][25]Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- leetcode 25 -- Reverse Nodes in k-Group
- [LeetCode-Algorithms-25] "Reverse Nodes in k-Group" (2017.9.28-WEEK4)
- ( Leetcode 25 ) Reverse Nodes in k-Group
- leetcode25: Reverse Nodes in k-Group
- [leetcode 25]Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- LeetCode(25)--Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- leetcode 25: Reverse Nodes in k-Group
- LeetCode 25 reverse-nodes-in-k-group
- Leetcode 25 Reverse Nodes in k-Group
- leetcode[25]Reverse Nodes in k-Group
- leetcode25---Reverse Nodes in k-Group
- leetcode 25:Reverse Nodes in k-Group
- LeetCode 25:Reverse Nodes in k-Group
- Leetcode 25 Reverse Nodes in k-Group