LeetCode 题解(178): Swap Nodes in Pairs

题目;

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题解:

递归,倒序交换。

C++版:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode *p = head, *q = head->next;
        dummy->next = swap(p, q);
        return dummy->next;
    }
    
    ListNode* swap(ListNode* p, ListNode* q) {
        if(q == NULL)
            return p;
        if(q->next == NULL) {
            p->next = NULL;
            q->next = p;
            return q;
        }
        q->next = swap(q->next, q->next->next);
        p->next = q->next;
        q->next = p;
        return q;
    }
};

Java版:

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null)
            return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = head, q = head.next;
        dummy.next = swap(p, q);
        return dummy.next;
    }
    
    public ListNode swap(ListNode p, ListNode q) {
        if(q == null)
            return p;
        if(q.next == null) {
            p.next = null;
            q.next = p;
            return q;
        }
        q.next = swap(q.next, q.next.next);
        p.next = q.next;
        q.next = p;
        return q;
    }
}

Python版:

class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def swapPairs(self, head):
        if head == None:
            return None
        dummy = ListNode(0)
        dummy.next = head
        p, q = head, head.next
        dummy.next = self.swap(p, q)
        return dummy.next
        
    def swap(self, p, q):
        if q == None:
            return p
        if q.next == None:
            p.next = None
            q.next = p
            return q
        q.next = self.swap(q.next, q.next.next)
        p.next = q.next
        q.next = p
        return q

你可能感兴趣的:(Algorithm,LeetCode,面试题)