leetcode 24. Swap Nodes in Pairs

leetcode 24. Swap Nodes in Pairs

题意:按下面规则反转链表

输入:1->2->3->4

输出:2->1->4->3

递归
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *    int val;
 *    ListNode* next;
 *    ListNode(int x): val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head -> next == NULL ) return NULL;

        ListNode* temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;

        return temp;
    }
};

非递归

class Solution {
public:
    
    ListNode* swap(ListNode* before,ListNode* head){
        before->next=head->next;
        head->next=head->next->next;
        before->next->next=head;
        return head;//下两组的before
    }
    
    ListNode* swapPairs(ListNode* head) {
        
        ListNode node(0);
        ListNode* root=&node;//领头
        root->next=head;
        
        ListNode* before=root;
        while(head!=NULL&&head->next!=NULL){
            before=swap(before,head);
            head=before->next;
        }
        
        return root->next;
    }
};


猜你喜欢

转载自blog.csdn.net/sea_muxixi/article/details/80191127