LeetCode 24. Swap Nodes in Pairs & 25. Reverse Nodes in k-Group

方法一:迭代

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy=new ListNode(0);
        dummy->next = head;
        ListNode *p=dummy;
        while (p->next && p->next->next){
            ListNode *q=p->next;
            ListNode *r=q->next;
            p->next = r;
            q->next = r->next;
            r->next = q;
            p = q;
        }
        return dummy->next;
    }
};

 

方法二:递归

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head==NULL) return NULL;
        if (head->next==NULL) return head;
        ListNode *tmp=swapPairs(head->next->next);
        ListNode *p=head->next;
        p->next = head;
        head->next = tmp;
        return p;
    }
};

 

25. Reverse Nodes in k-Group

递归非常好写,需要一个reverse函数,和翻转单链表写法类似,顺便复习。当然也可以迭代写,比较麻烦。

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *cur=head;
        for (int i=0;i<k;++i){
            if (cur==NULL) return head;
            cur = cur->next;
        }
        ListNode *newhead=reverse(head,cur);
        head->next = reverseKGroup(cur,k);
        return newhead;
    }
    
    ListNode *reverse(ListNode* head, ListNode* tail){ // not including tail
        ListNode *prev=tail, *curr=head;
        while (curr!=tail){
            ListNode *nextNode=curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextNode;
        }
        return prev;
    }
};

 

posted @ 2018-08-18 08:00  約束の空  阅读(109)  评论(0)    收藏  举报