[Leetcode]Swap Nodes in Pairs & Reverse Nodes in k-Group

 好几天没有继续了,最近压力好大,小小吐槽一下。为了恢复一些C/C++的能力,后面采用C++做了。(都被吐槽成重度java受害者了……TAT)

No.24, Swap Nodes in Pairs

No.25, Reverse Nodes in k-Group

第一个题是给定一个链表,每两个交换一下位置,例如1 2 3 4交换完是2 1 4 3

每两个交换的话,我这里保留了三个指针,其中两个是要交换的位置,还有一个是交换之前的位置,用来连接前一个节点和交换之后的节点。那么第一次交换的时候需要特殊处理。如果不想特殊处理,也可以新建一个头节点newHead,最后返回newHead的next即可。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *first, *second, *l;
        if(!head||!head->next)
            return head;
        first=head;
        second=first->next;
        head=second;
        l=first;
        while(second){
            l->next=second;
            first->next=second->next;
            second->next=first;
            l=first;
            first=first->next;
            if(!first)
                break;
            second=first->next;
        }
        return head;
    }
};

第二个题,在链表中,每k个节点逆序。这个问题可以拆分为两个小问题:①给定一段链表如何逆序,②如何每k个划分还能正确连接

那么对于第一个问题,可以采用的思路:从头上开始遍历,每遍历一个就把它放在最头上,作为新的head,例如1->2->3  变成 2->1->3再变成 3->2->1。这个过程并不是特别复杂,但是需要注意指针绕来绕去,在纸上画画会比较好。

第二个问题的坑在于如何正确连接,这也就是说我们必须有上一节最后的指针连接到新逆序的头节点上。这一点可以做在第一个问题中,也可以做在主函数中,在代码中我做在了第一个问题中,tail传入的就是上一个节点,它在函数中指向了逆序最后一个插到头上的节点。

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(k==1){
            return head;
        }
        ListNode *p=head;
        ListNode *h=new ListNode(0);
        h->next=head;
        ListNode *lasttail=h;
        int count=0;
        while(p){
            count++;
            if(count==k){
                ListNode *c=p->next;
                count=0;
                p->next=NULL;
                lasttail=reverseK(lasttail->next,lasttail);
                lasttail->next=c;
                p=c;
            }
            else
                p=p->next;
        }
        return h->next;
    }
    ListNode * reverseK(ListNode * head, ListNode * tail){
        ListNode *p=head->next;
        ListNode *q=head;
        while(p->next){
            q->next=p->next;
            ListNode *temp=p;
            p=p->next;
            temp->next=head;
            head=temp;
        }
        tail->next=p;
        tail=q;
        q->next=NULL;
        p->next=head;
        head=p;
        return tail;
    }
};
原文地址:https://www.cnblogs.com/lilylee/p/5257898.html