zoukankan      html  css  js  c++  java
  • 《剑指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;
               }
       };
    
    }
  • 相关阅读:
    时间计算
    DateTime
    C# trim split dataGrid
    something
    生活
    如何导入外部的源码到eclipse中
    java类中获取ServletContext的方法
    获取spring容器上下文(webApplicationContext)的几种方法
    java反射(转)
    mysql常见命令
  • 原文地址:https://www.cnblogs.com/t1amo/p/7087187.html
Copyright © 2011-2022 走看看