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
分析:初步来看问题是考察链表的插入和删除操作,但是增加了难度就在于:题目要求每K个节点翻转一次,并且需要注意的一点使当剩余节点小于k时,不需要进行翻转操作。
思路:
1、翻转链表操作是比较简单的,其核心代码如下:
//翻转节点head到节点tail的链表(不包括tail)
//返回当前翻转段的头节点
ListNode *reverse(ListNode *head, ListNode *tail){
ListNode *temp = head;
ListNode *reverHead = NULL;
ListNode *tempNext =NULL;
while(temp != tail){
tempNext = temp->next;
temp->next = reverHead;
reverHead = temp;
temp = tempNext;
}
head->next = tempNext;
return reverHead;
}
2、由此剩下的问题就是如何将原来链表划分为各个长度为k的小段的问题了,我的方法比较笨,就是设定一个计数器,计数器加到k就进行翻转,否则问题结束,返回结果:
class Solution{
public:
ListNode *reverseKGroup(ListNode *head,int k){
if(head==NULL||k<=1){
return head;
}
ListNode *pKHead = head;
ListNode *pKTail = head;
int i = 0;
//reverse the first k group
while(pKTail!=NULL&&i<k){
pKTail = pKTail->next;
i++;
}
if(i<k){
return head;
}
ListNode *pPreKHead = head;
head = reverse(pKHead,pKTail);
pKHead = pPreKHead->next;
while(pKHead!=NULL){
pKTail = pKHead;
i = 0;
while(pKTail!=NULL&&i<k){
pKTail = pKTail->next;
i++;
}
if(i<k) break;
ListNode *pPreNextKHead = pKHead;
pPreKHead->next = reverse(pKHead,pKTail);
pPreKHead = pPreNextKHead;
pKHead = pPreKHead->next;
}
return head;
}
private:
ListNode *reverse(ListNode *head, ListNode *tail){
ListNode *temp = head;
ListNode *reverHead = NULL;
ListNode *tempNext =NULL;
while(temp != tail){
tempNext = temp->next;
temp->next = reverHead;
reverHead = temp;
temp = tempNext;
}
head->next = tempNext;
return reverHead;
}
};