击鼓传花
function flower(num, arr) {
while (arr.length !== 1) {
for (var i = 0; i < num - 1; i++) {
item = arr.shift();
arr.push(item);
}
arr.shift()
}
return arr.shift()
}
console.log(flower(5, [1, 2, 3, 4, 5, 6]))
自定义集合
<script>
function set() {
this.items = {};
// 添加元素
set.prototype.add = function(item) {
if (this.has(item)) {
return false
}
this.items[item] = item;
return true
}
// 判断是否有某个元素
set.prototype.has = function(item) {
return this.hasOwnProperty(item)
}
// 删除元素
set.prototype.remove = function(item) {
if (!this.has(item)) return false;
delete this.items[item]
return true
}
// 清除所有
set.prototype.clear = function() {
this.items = {}
return true
}
// 判断长度
set.prototype.size = function() {
return Object.keys(this.items).length
}
// 返回内容
set.prototype.values = function() {
return Object.keys(this.items)
}
}
myset = new set();
myset.add('a')
myset.add('a')
myset.add('b')
myset.add('c')
myset.add('d')
myset.add(3)
myset.remove('a')
console.log(myset.size())
console.log(myset.values());
myset.clear()
console.log(myset.size())
</script>
自定义列表
<script>
function LinkedList() {
function Node(data) {
this.data = data;
this.next = null;
}
this.head = null;
this.length = 0;
LinkedList.prototype.append = function(data) {
var newNode = new Node(data)
if (this.length == 0) {
this.head = newNode
} else {
var current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode
}
this.length += 1;
}
LinkedList.prototype.toString = function() {
var current = this.head;
var listString = '';
while (current) {
listString += current.data + ' ';
current = current.next;
}
return listString;
}
LinkedList.prototype.insert = function(position, data) {
if (position < 0 || position > this.length) return false;
var newNode = new Node(data);
if (position == 0) {
//先给新的赋值才会比较好写
newNode.next = this.head;
this.head = newNode
} else {
var previous = null;
var current = this.head;
for (var index = 0; index < position; index++) {
previous = current;
current = current.next;
}
newNode.next = current;
previous.next = newNode;
}
this.length += 1;
return true
}
}
var list = new LinkedList();
list.append(3);
list.append(9);
list.append(0);
var str = list.toString()
console.log(str)
list.insert(3, 11);
console.log(list.toString())
</script>
该文章参考coderwhy的视频:https://www.bilibili.com/video/BV1nJ411J7a2