1. 程式人生 > >javaScript資料結構 04 連結串列

javaScript資料結構 04 連結串列

連結串列

連結串列儲存有序的元素集合。

01 就寫一個單向連結串列吧

;(function (window) {
  function Node(data) {
    this.data = data;
    this.next = null;
  }

  function Linklist() {
    this.length = 0;
    this.head = null;
  }
  Linklist.prototype.add = function (data) {
    var node = new Node(data);
    if (this
.length == 0) { this.head = node; } else { var tempHead = this.head; this.head = node; this.head.next = tempHead; } this.length++; } Linklist.prototype.insert = function (index, data) { if (index < 0 || index > this.length) { return false; } if
(index == 0) { this.add(data); return; } var node = new Node(data); var currentNode = this.head; for (var nodeIndex = 1; currentNode; currentNode = currentNode.next, nodeIndex++) { if (index == nodeIndex) { var currentNext = currentNode.next; currentNode.next = node; node.next = currentNext; } } this
.length++; } Linklist.prototype.pop = function () { var currentNode = this.head; this.head = currentNode.next; this.length--; } Linklist.prototype.remove = function (index) { if (index < 0 || index >= this.length) { return false; } if (index == 0) { this.pop(); return; } var currentNode = this.head; for (var nodeIndex = 1; currentNode; currentNode = currentNode.next, nodeIndex++) { if (index == nodeIndex) { var afterNext = currentNode.next.next; currentNode.next = afterNext; } } this.length--; } Linklist.prototype.get = function (index) { var rtnStr = new String(); if (index < 0 || index >= this.length) { return false; } var currentNode = this.head; for (var nodeIndex = 0; currentNode; currentNode = currentNode.next, nodeIndex++) { if (index == nodeIndex) { return currentNode.data; } } } Linklist.prototype.addAll = function (list) { var currentNode = this.head; for (var nodeIndex = 0; currentNode; currentNode = currentNode.next, nodeIndex++) { if (!currentNode.next) { currentNode.next = list.head; this.length += list.length; return; } } } Linklist.prototype.toArray = function () { var rtnList = new Array(); var currentNode = this.head; rtnList.push(currentNode.data); for (; currentNode.next; currentNode = currentNode.next) { rtnList.push(currentNode.next.data); } return rtnList; } Linklist.prototype.toString = function () { var arrayList = this.toArray(); return arrayList.toString(); } window.Linklist = Linklist; })(window);