Javascript的数据结构与算法(一)

1数组

1.1要领列表

数组的经常运用要领以下:

  • concat: 链接两个或许更多数据,并返回效果。

  • every: 对数组中的每一项运转给定的函数,假如该函数对每一项都返回true,则返回true。

  • filter: 对数组中的每一项运转给定函数,返回改函数会返回true的项构成的数组。

  • forEach: 对数组中的每一项运转给定函数,这个要领没有返回值。

  • join: 将一切的数组元素链接成一个字符串。

  • indexOf: 返回第一个与给定参数相称的数组元素的索引,没有找到则返回-1。

  • lastIndexOf: 返回在数组中搜刮到的与给定参数相称的元素的索引里最大的值。

  • map: 对数组中的每一项运转给定函数,返回每次函数挪用的效果构成的数组。

  • reverse: 倒置数组中元素的递次,本来第一个元素如今变成末了一个,一样本来的末了一个元素变成如今的第一个。

  • slice: 传入索引值,将数组中对应索引范围内的元素作为新元素返回。

  • some: 对数组中的每一项运转给定函数,假如任一项返回true,则返回true。

  • sort: 依据字母递次对数组排序,支撑传入指定排序要领的函数作为参数。

  • toString: 将数组作为字符串返回。

  • valueOf: 和toString类似,将数组作为字符串返回。

1.2数组兼并

concat要领能够向一个数组通报数组、对象或是元素。数组会依据该要领传入的参数递次 衔接指定数组。

    var zero = 0;
    var positiveNumbers = [1,2,3];
    var negativeNumbers = [-1,-2,-3];
    var numbers = negativeNumbers.concat(zero,positiveNumbers);
    console.log(numbers);//输出效果: [-1, -2, -3, 0, 1, 2, 3]

1.3迭代器函数

reduce要领吸收一个函数作为参数,这个函数有四个参数:previousValue、currentValue、index和array。这个函数会返回一个将被叠加到累加器的 值,reduce要领住手实行后会返回这个累加器。假如要对一个数组中的一切元素乞降,这就很有用了。

    var isEven = function(x){
      return (x%2 == 0)?true:false;
    }
    var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
    //every要领会迭代数组中的每一个元素,直到返回false。
    var result = numbers.every(isEven);
    console.log(result);//false
    //some要领会迭代数组的每一个元 素,直到函数返回true.
    result = numbers.some(isEven);
    console.log(result);//true
    //forEach对每一项运转给定的函数,没有返回值
    numbers.forEach(function(item,index){
      console.log(item%2 == 0);
    });
    //map会迭代数组中的每一个值,而且返回迭代效果
    var myMap = numbers.map(isEven);
    console.log(myMap);// [false, true, false, true, false, true, false, true, false, true, false, true, false, true, false]
    //filter要领返回的新数组由使函数返回true的元素构成
    var myFilter = numbers.filter(isEven);
    console.log(myFilter);// [2, 4, 6, 8, 10, 12, 14]
    //reduct函数
    var myReduce = numbers.reduce(function(previous,current,index){
      return previous + "" + current;
    });
    console.log(myReduce);//123456789101112131415

1.4排序

    var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
    numbers.reverse();//[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    function compare(a,b){
      if(a > b){
        return 1;
      }
      if(a < b){
        return -1;
      }
      return 0;
    }
    //sort函数运用
    [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9].sort(compare);

    var friends = [{
      name:'huang',
      age:30
    },{
      name:'chengdu',
      age:27
    },{
      name:'du',
      age:31
    }];
    function comparePerson(a,b){
      if(a.age > b.age){
        return 1;
      }
      if(a.age < b.age){
        return -1;
      }
      return 0;
    }
    console.log(friends.sort(comparePerson));// [Object { name="chengdu",  age=27}, Object { name="huang",  age=30}, Object { name="du",  age=31}]
    //搜刮
    numbers.push(10);
    console.log(numbers.indexOf(10));//5
    console.log(numbers.lastIndexOf(10));//15
    var numbersString = numbers.join('-');
    console.log(numbersString);//15-14-13-12-11-10-9-8-7-6-5-4-3-2-1-10

2栈

2.1栈的建立

关于一个栈,我们须要完成增加、删除元素、猎取栈顶元素、已是不是为空,栈的长度、消灭元素等几个基础操纵。下面是基础定义。

    function Stack(){
      this.items = [];
    }
    Stack.prototype = {
      constructor:Stack,
      push:function(element){
        this.items.push(element);
      },
      pop:function(){
        return this.items.pop();
      },
      peek:function(){
        return this.items[this.items.length - 1];
      },
      isEmpty:function(){
        return this.items.length == 0;
      },
      clear:function(){
        this.items = [];
      },
      size:function(){
        return this.items.length;
      },
      print:function(){
        console.log(this.items.toString());
      }
    }

2.2栈的基础运用

栈的基础操纵。

    var stack = new Stack();
    console.log(stack.isEmpty());//true
    stack.push(5);
    stack.push(8);
    console.log(stack.peek());//8
    stack.push(11);
    console.log(stack.size());//3
    console.log(stack.isEmpty());
    stack.push(15);
    stack.pop();
    stack.pop();
    console.log(stack.size());//2
    console.log(stack.print());//5,8

经由过程栈完成对正整数的二进制转换。

    function divideBy2(decNumber){
      var decStack = new Stack();
      var rem;
      var decString = '';
      while(decNumber > 0){
        rem = decNumber%2;
        decStack.push(rem);
        decNumber = Math.floor(decNumber/2);
      }
      while(!decStack.isEmpty()){
        decString += decStack.pop().toString();
      }
      return decString;
    }
    console.log(divideBy2(10));//1010

3行列

3.1行列的建立

行列是遵照FIFO(First In First Out,先进先出,也称为先来先效劳)准绳的一组有序的项。行列在尾部增加新元素,并从顶部移除元素。最新增加的元素必需排在行列的末端。行列要完成的操纵基础和栈一样,只不过栈是FILO(先进后出)。

    function Queue(){
      this.items = [];
    }
    Queue.prototype = {
      constructor:Queue,
      enqueue:function(elements){
        this.items.push(elements);
      },
      dequeue:function(){
        return this.items.shift();
      },
      front:function(){
        return this.items[0];
      },
      isEmpty:function(){
        return this.items.length == 0;
      },
      size:function(){
        return this.items.length;
      },
      clear:function(){
        this.items = [];
      },
      print:function(){
        console.log(this.items.toString());
      }
    }

行列的基础运用

    var queue = new Queue();
    console.log(queue.isEmpty());//true
    queue.enqueue('huang');
    queue.enqueue('cheng');
    console.log(queue.print());//huang,cheng
    console.log(queue.size());//2
    console.log(queue.isEmpty());//false
    queue.enqueue('du');
    console.log(queue.dequeue());//huang
    console.log(queue.print());//cheng,du

3.2 优先行列

元素的增加和移除是基于优先级的。完成一个优先行列,有两种选项:设置优先级,然后在准确的位置增加元素;或许用入列操 作增加元素,然后依据优先级移除它们。
我们在这里完成的优先行列称为最小优先行列,由于优先级的值较小的元素被安排在行列最 前面(1代表更高的优先级)。最大优先行列则与之相反,把优先级的值较大的元素安排在行列最 前面。

3.2.1 优先行列的定义

我们在这里运用组合继续的体式格局继续自Queue行列。

    function PriorityQueue(){
      Queue.call(this);
    };
    PriorityQueue.prototype = new Queue();
    PriorityQueue.prototype.constructer = PriorityQueue;
    PriorityQueue.prototype.enqueue = function(element,priority){
      function QueueElement(tempelement,temppriority){
        this.element = tempelement;
        this.priority = temppriority;
      }
      var queueElement = new QueueElement(element,priority);
      if(this.isEmpty()){
        this.items.push(queueElement);
      }else{
        var added = false;
        for(var i = 0; i < this.items.length;i++){
          if(this.items[i].priority > queueElement.priority){
            this.items.splice(i,0,queueElement);
            added = true;
            break;
          }
        }
        if(!added){
            this.items.push(queueElement);
        }
      }
      
    }
    //这个要领能够用Queue的默许完成
    PriorityQueue.prototype.print = function(){
      var result ='';
      for(var i = 0; i < this.items.length;i++){
        result += JSON.stringify(this.items[i]);
      }
      return result;
    }

3.2.1 优先行列的基础运用

    var priorityQueue = new PriorityQueue();
    priorityQueue.enqueue("cheng", 2);
    priorityQueue.enqueue("du", 3);
    priorityQueue.enqueue("huang", 1);
    console.log(priorityQueue.print());//{"element":"huang","priority":1}{"element":"cheng","priority":2}{"element":"du","priority":3}
    console.log(priorityQueue.size());//3
    console.log(priorityQueue.dequeue());//{ element="huang",  priority=1}
    console.log(priorityQueue.size());//2

3链表

数组的大小是牢固的,从数组的出发点或中心插进去 或移除项的本钱很高,由于须要挪动元素(只管我们已学过的JavaScript的Array类要领能够帮 我们做这些事,但背地的状况一样是如许)。链表存储有序的元素鸠合,但差别于数组,链表中的元素在内存中并非一连安排的。每一个 元素由一个存储元素自身的节点和一个指向下一个元素的援用(也称指针或链接)构成。

相关于传统的数组,链表的一个优点在于,增加或移除元素的时刻不须要挪动其他元素。然 而,链表须要运用指针,因而完成链表时须要分外注重。数组的另一个细节是能够直接接见任何 位置的任何元素,而要想接见链表中心的一个元素,须要从出发点(表头)最先迭代列表直到找到 所需的元素

3.1.1链表的建立

我们运用动态原型形式来建立一个链表。列表末了一个节点的下一个元素始终是null。

    function LinkedList(){
      function Node(element){
        this.element = element;
        this.next = null;
      }
      this.head = null;
      this.length = 0;
      //经由过程对一个要领append推断就能够晓得是不是设置了prototype
      if((typeof this.append !== 'function')&&(typeof this.append !== 'string')){
        //增加元素
        LinkedList.prototype.append = function(element){
          var node = new Node(element);
          var current;
          if(this.head === null){
            this.head = node;
          }else{
            current = this.head;
            while(current.next !== null){
              current = current.next;
            }
            current.next = node;
          }
          this.length++;
        };
        //插进去元素,胜利true,失利false
        LinkedList.prototype.insert = function(position,element){
          if(position > -1 && position < this.length){
            var current = this.head;
            var previous;
            var index = 0;
            var node = new Node(element);
            if(position == 0){
              node.next = current;
              this.head = node;
            }else{
              while(index++ < position){
                previous = current;
                current = current.next;
              }
              node.next = current;
              previous.next = node;
            }
            this.length++;
            return true;
          }else{
            return false;
          }
        };
        //依据位置删除指定元素,胜利 返回元素, 失利 返回null
        LinkedList.prototype.removeAt = function(position){
          if(position > -1 && position < this.length){
            var current = this.head;
            var previous = null;
            var index = 0;
            if(position == 0){
              this.head = current.next;
            }else{
              while(index++ < position){
                previous = current;
                current = current.next;
              }
              previous.next = current.next;
            }
            this.length--;
            return current.element;
          }else{
            return null;
          }
        };
        //依据元素删除指定元素,胜利 返回元素, 失利 返回null
        LinkedList.prototype.remove = function(element){
          var index = this.indexOf(element);
          return this.removeAt(index);
        };
        //返回给定元素的索引,假如没有则返回-1
        LinkedList.prototype.indexOf = function(element){
          var current = this.head;
          var index = 0;
          while(current){
            if(current.element === element){
              return index;
            }
            index++;
            current = current.next;
          }
          return -1;
        };
        LinkedList.prototype.isEmpty = function(){
          return this.length === 0;
        };
        LinkedList.prototype.size = function(){
          return this.length;
        };
        LinkedList.prototype.toString = function(){
            var string = '';
            var current = this.head;
            while(current){
              string += current.element;
              current = current.next;
            }
            return string;
        };
        LinkedList.prototype.getHead = function(){
          return this.head;
        };
      }
    }

3.1.2链表的基础运用

    var linkedList = new LinkedList();
    console.log(linkedList.isEmpty());//true;
    linkedList.append('huang');
    linkedList.append('du')
    linkedList.insert(1,'cheng');
    console.log(linkedList.toString());//huangchengdu
    console.log(linkedList.indexOf('du'));//2
    console.log(linkedList.size());//3
    console.log(linkedList.removeAt(2));//du
    console.log(linkedList.toString());//huangcheng

3.2.1双向链表的建立

链表有多种差别的范例,这一节引见双向链表。双向链表和一般链表的区分在于,在链表中, 一个节点只要链向下一个节点的链接,而在双向链表中,链接是双向的:一个链向下一个元素, 另一个链向前一个元素。

双向链表和链表的区分就是有一个tail属性,所以必需重写insert、append、removeAt要领。每一个节点对应的Node也多了一个prev属性。

   //寄生组合式继续完成,详见javascript高等程序设计第七章
   function inheritPrototype(subType, superType) {
       function object(o) {
           function F() {}
           F.prototype = o;
           return new F();
       }
       var prototype = object(superType.prototype);
       prototype.constructor = subType;
       subType.prototype = prototype;
   }
   function DoublyLinkedList() {
       function Node(element) {
           this.element = element;
           this.next = null;
           this.prev = null;
       }
       this.tail = null;
       LinkedList.call(this);
       //与LinkedList差别的要领本身完成。
       this.insert = function(position, element) {
           if (position > -1 && position <= this.length) {
               var node = new Node(element);
               var current = this.head;
               var previous;
               var index = 0;
               if (position === 0) {
                   if (!this.head) {
                       this.head = node;
                       this.tail = node;
                   } else {
                       node.next = current;
                       current.prev = node;
                       this.head = node;
                   }
               } else if (position == this.length) {
                   current = this.tail;
                   current.next = node;
                   node.prev = current;
                   this.tail = node;
               } else {
                   while (index++ < position) {
                       previous = current;
                       current = current.next;
                   }
                   previous.next = node;
                   node.next = current;
                   current.prev = node;
                   node.prev = previous;
               }
               this.length++;
               return true;
           } else {
               return false;
           }
       };
       this.append = function(element) {
           var node = new Node(element);
           var current;
           if (this.head === null) {
               this.head = node;
               this.tail = node;
           } else {
               current = this.head;
               while (current.next !== null) {
                   current = current.next;
               }
               current.next = node;
               node.prev = current;
               this.tail = node;
           }
           this.length++;
       };
       this.removeAt = function(position) {
           if (position > -1 && position < this.length) {
               var current = this.head;
               var previous;
               var index = 0;
               if (position === 0) {
                   this.head = current.next;
                   if (this.length === 1) {
                       this.tail = null;
                   } else {
                       this.head.prev = null;
                   }
               } else if (position === (this.length - 1)) {
                   current = this.tail;
                   this.tail = current.prev;
                   this.tail.next = null;
               } else {
                   while (index++ < position) {
                       previous = current;
                       current = current.next;
                   }
                   previous.next = current.next;
                   current.next.prev = previous;
               }
               this.length--;
               return current.element;
           } else {
               return false;
           }
       };
   }
   inheritPrototype(DoublyLinkedList, LinkedList);

3.2.2双向链表的基础运用

    var doublyList = new DoublyLinkedList();
    console.log(doublyList.isEmpty()); //true;
    doublyList.append('huang');
    doublyList.append('du')
    doublyList.insert(1, 'cheng');
    console.log(doublyList.toString()); //huangchengdu
    console.log(doublyList.indexOf('du')); //2
    console.log(doublyList.size()); //3
    console.log(doublyList.removeAt(2)); //du
    console.log(doublyList.toString()); //huangcheng

3.2.3 轮回链表

轮回链表能够像链表一样只要单向援用,也能够像双向链表一样有双向援用。轮回链表和链 表之间唯一的区分在于,末了一个元素指向下一个元素的指针(tail.next)不是援用null, 而是指向第一个元素(head)。双向轮回链表有指向head元素的tail.next,和指向tail元素的head.prev。

源码地点

Javascript的数据结构与算法(一)源码

    原文作者:huang303513
    原文地址: https://segmentfault.com/a/1190000007907302
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞