LeetCode-Reverse Nodes in k-Group-按组翻转链表-链表操作

https://oj.leetcode.com/problems/reverse-nodes-in-k-group/

使用一个计数器cn,当cn%k=0时进行翻转,翻转时需要把这组链表前面的一个节点的next值也做相应的设置。并且翻转后最后一个节点的next值也需要设置。考虑这些之后小心操作链表即可,如果想要一次写出bug-free的代码则需要仔细考虑链表的各处指针是否正确。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void Reverse(ListNode *in,ListNode *out,ListNode *&h,ListNode *&t){
        ListNode *p=h;
        while(h->next!=out){
            ListNode *q=h->next;
            h->next=q->next;
            q->next=p;
            if (in!=NULL) in->next=q;
            p=q;
        }
        t=h;
        h=p;
    }
    ListNode *reverseKGroup(ListNode *head, int k) {
        if (head==NULL) return NULL;
        ListNode *l=head;
        ListNode *r=head;
        ListNode *lp=NULL;
        ListNode *h=head;
        bool first=false;
        int cn=1;
        while(r!=NULL){
            if (cn%k==0) {
                Reverse(lp,r->next,l,r);
                if (!first){
                    h=l;
                    first=true;
                }
                lp=r;
                l=r->next;
            }
            r=r->next;
            cn++;
        }
        return h;
    }
};

  

posted @ 2014-10-10 23:18  zombies  阅读(149)  评论(0编辑  收藏  举报