24.md

December 16, 2019 · View on GitHub

:pencil2:Leetcode之PHP版题目解析(24. Swap Nodes in Pairs)

2019-12-16 吴亲库里 库里的深夜食堂


:pencil2:描述

给定一个链表,两两交换两个结点的位置,然后返回交换后的链表,注意是交换结点本身,而不是修改其值


:pencil2:题目实例

****

:pencil2:题目分析

递归非递归都可以实现,就是需要去修改指针的指向,感觉做这种题目自己去画下图模拟下,不然可能在改变 next 的时候容易把自己绕晕。


:pencil2:代码实现(递归)

 

   /**
     * @param ListNode $head
     * @return ListNode
     */
    function swapPairs($head) {
        if($head ==null || $head->next==null){
            return $head;
        }
        $temp=$head->next;
        $head->next=$this->swapPairs($temp->next);
        $temp->next=$head;    
        return $temp;
    }

:pencil2:代码实现(非递归)

    /**
      * @param ListNode $head
      * @return ListNode
      */
     function swapPairs($head) {     
         $pre=new ListNode(-1);
         $pre->next=$head;
         $tmp=$pre;
         while($tmp->next !=null && $tmp->next->next !=null){
             $start=$tmp->next;
             $end=$tmp->next->next;
             $tmp->next=$end;
             $start->next=$end->next;
             $end->next=$start;
             $tmp=$start;
         }
         return $pre->next;
     }

联系