Skip to content

Latest commit

 

History

History
62 lines (52 loc) · 1.64 KB

206.md

File metadata and controls

62 lines (52 loc) · 1.64 KB

✏️Leetcode之PHP版题目解析(206. Reverse Linked List)

2019-04-01 吴亲库里 库里的深夜食堂


✏️描述

反转单链表


✏️题目实例

****

✏️题目分析

题目让我们用两种方式实现,一种迭代一种递归.遍历链表的时候,只要吧当前节点的下一个指针指向更改为它的上一个节点,更改的时候需要用另一个指针来存储下一个节点。

     /**
          * @param ListNode $head
          * @return ListNode
          */
         function reverseList($head) {
             $prev=null;
             $curr=$head;
             while($curr !==null){
                 $nextcode=$curr->next;
                 $curr->next=$prev;
                 $prev=$curr;
                 $curr=$nextcode;
             }
             return $prev;  
         }

✏️解法二

递归

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

联系