# 数据结构

本节主要练习,用 JS 实现各种数据结构

# List

function List() {
  this.listSize = 0;
  this.pos = 0; // 当前位置
  this.dataStore = [];
  this.clear = clear;
  this.find = find;
  this.toString = toString;
  this.insert = insert;
  this.append = append;
  this.remove = remove;
  this.front = front; //从当前位置移动到第一个
  this.end = end; //从当前位置移动到最后一个
  this.prev = prev; // 前移1位
  this.next = next; //后移一位
  this.length = length;
  this.currPos = currPos;
  this.moveTo = moveTo;
  this.getElement = getElement;
  this.contains = contains;
}

function append(element) {
  this.dataStore[this.listSize++] = element;
}

function find(element) {
  for (var i = 0; i < this.listSize; i += 1) {
    if (this.dataStore[i] == element) {
      return i;
    }
  }
  return -1;
}

function remove(element) {
  var index = this.find(element);
  if (index > -1) {
    this.dataStore.slice(index, 1);
    --this.listSize;
    return true;
  }
  return false;
}

function length() {
  return this.listSize;
}
// ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

#

其实是不需要的,数组现在默认就能实现栈的所有功能。

function Stack() {
  this.dataStore = [];
  this.top = 0; // 标记可以插入新元素的位置
  this.push = push; // 入栈操作
  this.pop = pop;
  this.peek = peek;
  this.clear = clear;
  this.length = length;
}

function push(element) {
  this.dataStore(this.top++) = element;
}

// 返回栈顶元素
function pop() {
  this.top--;
  return this.dataStore.pop();
}

function peek() {
  return this.dataStore[this.top - 1];
}

function length() {
  this.top;
}

function clear() {
  this.dataStore = [];
  this.top = 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 回文

应用在回文字符串里

function isPalindrome(word) {
  var s = [];
  for (var i = 0; i < word.length; i++) {
    s.push(word[i]);
  }
  var reverse = "";
  while (s.length() > 0) {
    reverse += s.pop();
  }
  if (reverse == word) {
    return true;
  }
  return fasle;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 链表

最后更新时间: 1/25/2021, 2:35:02 PM