• 《剑指offer》— JavaScript(3)从尾到头打印链表


    从尾到头打印链表

    题目描述

      输入一个链表,从尾到头打印链表每个节点的值。


    实现代码

    /*function ListNode(x){
        this.val = x;
        this.next = null;
    }*/
    function printListFromTailToHead(head)
    {
        var res=[];
        while(head){
            res.unshift(head.val);
            head=head.next;
        }
        return res;
    }

    相关知识

    创建一个链表,并实现插入,删除,添加的方法

    function  LinkedList(){
       var Node=function(val){
             this.val=val;
             this.next=null;
       }
    
       var length=0;
       var head=null;
    
       this.append=function(val){
          var node=new Node(val),
              current;
          if (head==null) {
              head=node;
          }else{
              current=head;
    
              while(current.next){
                  current=current.next;
              }
    
              current.next=node;
          }
    
          length++;
       };
    
       this.removeAt=function(pos){
             if (pos>-1 && pos<length) {
            var current=head,
                previous,
                index=0;
    
            if (pos===0) {
               head=current.next;
            }else{
                while(index++<pos){
                    previous=current;
                    current=current.next;
                }
                length--;
                previous.next=current.next;
            }
             }else{
                 return null;
             }
       };
    
       this.insertAt=function(pos,val){
               if (pos>=0 && pos <=length) {
                   var node=new Node(),
                       current=head,
                       previous,
                       index=0;
    
                if (pos===0) {
                    head=node;
                }else{
                    while(index++<pos){
                        previous=current;
                        current=current.next;
                    }
                    node.next=current;
                    previous.next=node;
                }
                length++;
                return true;
               }else{
                   return null;
               }
       };
    
    }
  • 相关阅读:
    Docker
    Dotted lines by default in ViVA
    8245H(C2)光猫配置方法
    两种将verilog网表转为spice网表的方法
    calibredrv create reference cell
    怎么flatten一个GDS所有层次
    路由器后面访问光猫
    贝尔IPTV
    PDK导出的cdl MOS四端顺序不正确
    如何删除已经存在lib的techfile
  • 原文地址:https://www.cnblogs.com/t1amo/p/7087187.html
Copyright © 2020-2023  润新知