LeetCode题目-206

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2017-12-26 09:33:00

简介 LeetCode题目-206


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


✏描述

反转单链表


✏题目实例


✏题目分析

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

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

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云