Reverse Nodes in k-Group
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.
总体来说,不过是以链表反转的加强版而已。
具体的思想是,我们将要整个链表看做是几个链表的组成,分别对每个链表进行反转,在反转的时候将反转的链表进行连接。
struct ListNode* reverseKGroup(struct ListNode* head, int k) { int len=0; struct ListNode* t=head; //统计链表数目 while(t!=NULL){ len++; t=t->next; } if(len==0||k>len||k<=1)return head; struct ListNode* newHead=NULL; struct ListNode* cur=head; //头插入法,构建新的链表 for(int i=0;i<k;i++){ struct ListNode* temp=cur->next; cur->next=newHead; newHead=cur; cur=temp; } head->next=reverseKGroup(cur,k); return newHead; }
posted on 2016-11-25 22:45 lichao_normal 阅读(71) 评论(0) 收藏 举报
浙公网安备 33010602011771号