Javascript的數據結構與算法(一)

1數組


1.1方法列表

數組的經常使用方法以下:javascript

  • concat: 連接兩個或者更多數據,並返回結果。java

  • every: 對數組中的每一項運行給定的函數,若是該函數對每一項都返回true,則返回true。node

  • filter: 對數組中的每一項運行給定函數,返回改函數會返回true的項組成的數組。git

  • forEach: 對數組中的每一項運行給定函數,這個方法沒有返回值。github

  • join: 將全部的數組元素連接成一個字符串。算法

  • indexOf: 返回第一個與給定參數相等的數組元素的索引,沒有找到則返回-1。數組

  • lastIndexOf: 返回在數組中搜索到的與給定參數相等的元素的索引裏最大的值。數據結構

  • map: 對數組中的每一項運行給定函數,返回每次函數調用的結果組成的數組。app

  • reverse: 顛倒數組中元素的順序,原先第一個元素如今變成最後一個,一樣原先的最後一個元素變成如今的第一個。ide

  • 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的數據結構與算法(一)源碼

相關文章
相關標籤/搜索