43-Reverse Nodes in k-Group

来源:互联网 发布:企业网络拓扑结构图 编辑:程序博客网 时间:2024/05/22 09:48
  1. Reverse Nodes in k-Group My Submissions QuestionEditorial Solution
    Total Accepted: 58690 Total Submissions: 212820 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

当之无愧的难题,其实思路比较简明,但是要写出完全无bug的代码简直太难了,改了很多遍才改到无bug,因为里面的指针运算太多了,一不注意就掉坑了,改变了指针所向内容的next,确仍然引用

结果:
Submission Details

81 / 81 test cases passed.

Status: Accepted

Runtime: 24 ms

beats:41.82%

思路:找到每一段末尾标记,然后该段范围内进行逆转,同时保留逆转后的末尾元素。

class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        if(head==NULL||head->next==NULL||k==1)return head;        ListNode *fir=head,*sec=head,*pre_fir=NULL,*pre_sec=NULL;        int finished=0;        int count=1;        while(!finished){            int i=1;            while(i++<k&&sec!=NULL){sec=sec->next;} //fir.....sec段总的K个元素            ListNode *sec_next=(sec==NULL)?NULL:sec->next;            if((i-1)==k&&(sec!=NULL)){          //注意,只有当找了k次且最后一次找到了(不为空)才进行这段元素原地逆转                ListNode *tmp = fir->next;   //逆转时的当前元素                ListNode *prenode = fir;   //逆转时保留的前一元素                while(tmp!=sec_next) //当前元素没到sec末尾元素,                {                      ListNode *nextnode = (tmp->next); //保存当前元素的下一元素                    tmp->next = prenode;          //当前元素指向前一个元素                    prenode = tmp;                //前一元素右移                    tmp = nextnode;               //当前元素右移                 }                 fir->next = NULL;         //第一段的首元素变成末尾元素。                 if(pre_fir!=NULL){pre_fir->next = prenode;pre_fir = fir;}//pre_fir上一段逆转后的末尾指向当前的逆转后的开头                 else {head = prenode;pre_fir=fir;}//针对第一次前一段的逆转前的为空                 fir = sec_next;  //开始下一段元素逆转,sec_next保存上一段sec的下一元素                 sec = fir;      //将sec置为fir一样的值,开始逆转流程。            }            else {                    finished = 1;                    if(pre_fir!=NULL)pre_fir->next = fir;            }        }        return head;    }};
0 0