Total Accepted: 41856
Total Submissions: 165382
Difficulty: Hard
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: 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) {
if( k == 1 || head == NULL)
return head;
ListNode *Node_pre = new ListNode(-1);
Node_pre->next = head;
ListNode *Node_cur = head, *Node_head = Node_pre, *Node_next = Node_cur->next, *Node_tmp,*Node_mark,*Node_start,*Node_end;
int count = 0;
while(1)
{
//判断够不够K个
Node_tmp = Node_cur;
count =0;
while( Node_tmp && count < k)
{
count ++;
Node_tmp = Node_tmp->next;
}
if( count < k)
{
Node_pre->next = Node_cur;
return Node_head->next;
}
Node_mark = Node_tmp;
Node_end = Node_cur;
//进行链表翻转
while( Node_cur != Node_mark && Node_next)
{
Node_tmp = Node_next->next;
Node_next->next = Node_cur;
Node_cur = Node_next;
Node_next = Node_tmp;
}
if( Node_cur != Node_mark)
{
Node_pre->next = Node_cur;
Node_end->next = NULL;
return Node_head->next;
}
Node_pre->next = Node_cur->next;
Node_pre = Node_end;
Node_cur->next = Node_next;
}
}
};