两两交换链表中的节点(leetcode 24)

一:解题思路

方法一:递归法 Time:O(n),Space:O(n)

方法二:迭代法 Time:O(n),Space:O(1)

二:完整代码示例 (C++、Java、Python)

方法一C++:

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

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

        return next;
    }
};

方法二C++:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) 
    {
        if (head == NULL || head->next == NULL) return head;
        ListNode* dummy = new ListNode(0);
        ListNode* pre = dummy;
        dummy->next = head;

        while (pre->next != NULL && pre->next->next != NULL)
        {
            ListNode* first = pre->next;
            ListNode* second = pre->next->next;

            pre->next = second;
            first->next = second->next;
            second->next = first;
            pre = first;
        }

        return dummy->next;
    }
};

方法一Java:

class Solution {
        public ListNode swapPairs(ListNode head) {
                if(head==null || head.next==null) return head;
                
                ListNode next=head.next;
                head.next=swapPairs(next.next);
                next.next=head;
                
                return next;
        }
    }

方法二Java:

class Solution {
        public ListNode swapPairs(ListNode head)
        {
               if(head==null || head.next==null) return head;
               
               ListNode dummy=new ListNode(0);
               dummy.next=head;
               ListNode pre=dummy;
               
               while(pre.next!=null && pre.next.next!=null)
               {
                   ListNode first=pre.next;
                   ListNode second=pre.next.next;
                   
                   pre.next=second;
                   first.next=second.next;
                   second.next=first;
                   pre=first;
               }
               
               return dummy.next;
        }
    }

方法一Python:

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head==None: return head
        if head.next==None: return head
        
        next=head.next
        head.next=self.swapPairs(next.next)
        next.next=head
        
        return next

方法二Python:

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head==None: return head
        if head.next==None: return head
        
        dummy=self
        dummy.next=head
        pre=dummy
        
        while pre.next and pre.next.next:
            first=pre.next
            second=pre.next.next
            pre.next=second
            first.next=second.next
            second.next=first
            pre=first
        return dummy.next

 

posted @ 2020-04-15 21:14  repinkply  阅读(135)  评论(0)    收藏  举报