LeetCode题目-19

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2016-11-20 09:04:32

简介 LeetCode题目-19


✏Leetcode之PHP版题目解析(19. Remove Nth Node From End of List)


✏描述

给定一个链表和一个随机数(随机数在可操作范围内),从链表的后面开始,移除倒数第n个节点,返回新的链表。


✏题目实例


✏题目分析

删除倒数第n个节点,也就是删除链表第Length-n+1个节点,所以第一步先求出链表的长度,第二步就是开始正式找删除节点了,通过指针的移动,先确认Lenght-n的位置,这个位置的下一个位置就是待删除的节点,我们只需要把这个位置的next指针指向他的->next->next即可。


✏解法一

      /**
       * Definition for a singly-linked list.
       * class ListNode {
       *     public $val = 0;
       *     public $next = null;
       *     function __construct($val) { $this->val = $val; }
       * }
       */
      class Solution {
      
          /**
           * @param ListNode $head
           * @param Integer $n
           * @return ListNode
           */
         
          function removeNthFromEnd($head, $n) {
            $temp->next=$head;
            $node=$head;
              $count=0;
              while($node !=null){
                  $count++;
                  $node=$node->next;
              }
              $count -=$n;
              $node=$temp;
              
              while($count>0){
                  $count--;
                  $node=$node->next;
              }
              $node->next=$node->next->next;
              return $temp->next;
          }
      }

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


Tags:


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


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


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云