美文网首页
5_7链表的k逆序

5_7链表的k逆序

作者: X_Y | 来源:发表于2017-09-14 21:46 被阅读9次

    有一个单链表,请设计一个算法,使得每K个节点之间逆序,如果最后不够K个节点一组,则不调整最后几个节点。例如链表1->2->3->4->5->6->7->8->null,K=3这个例子。调整后为,3->2->1->6->5->4->7->8->null。因为K==3,所以每三个节点之间逆序,但其中的7,8不调整,因为只有两个节点不够一组。

    给定一个单链表的头指针head,同时给定K值,返回逆序后的链表的头指针。

    /*
       struct ListNode {
       int val;
       struct ListNode *next;
       ListNode(int x) : val(x), next(NULL) {}
       };*/
    class KInverse {
        public:
            ListNode* inverse(ListNode* head, int k) {
                // write code here
                int cnt = 1;
                ListNode *first = head, *curr = head, *next_gp = head,
                         *local_curr = head, *pre_end = head, *local_pre=head, *local_nxt = head;
                while(curr){
                    if(k == cnt){
                        // 记录第一段需要反转的段前和段后
                        head = curr;
                        next_gp = curr->next;
                        local_pre = next_gp;
                        // 反转内部节点
                        while(local_curr != next_gp){
                            local_nxt = local_curr->next;
                            local_curr->next = local_pre;
                            local_pre = local_curr;
                            local_curr = local_nxt;
                        }
                        // 为下次做准备
                        curr = first;
                        first = next_gp;
                        pre_end = curr;
                    }else if(cnt > k && 0 == cnt%k){
                        // 记录段前和段后,并将收尾相连
                        pre_end->next = curr;
                        next_gp = curr->next;
                        local_pre = next_gp;
                        local_curr = first;
                        // 反转内部节点
                        while(local_curr != next_gp){
                            local_nxt = local_curr->next;
                            local_curr->next = local_pre;
                            local_pre = local_curr;
                            local_curr = local_nxt;
                        }
                        // 为下次做准备
                        curr = first;
                        first = next_gp;
                        pre_end = curr;
                    }
                    curr = curr->next;
                    ++cnt;
                }
                return head;
            }
    };
    

    相关文章

      网友评论

          本文标题:5_7链表的k逆序

          本文链接:https://www.haomeiwen.com/subject/fidjsxtx.html