Skip to content

Latest commit

 

History

History
74 lines (56 loc) · 1.88 KB

24.md

File metadata and controls

74 lines (56 loc) · 1.88 KB

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

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


✏️描述

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


✏️题目实例

****

✏️题目分析

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


✏️代码实现(递归)

 

   /**
     * @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;
    }

✏️代码实现(非递归)

    /**
      * @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;
     }

联系