-
Notifications
You must be signed in to change notification settings - Fork 0
/
doublyLinkedListes5.js
127 lines (113 loc) · 2.69 KB
/
doublyLinkedListes5.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
function Node (ele) {
this.element = ele;
this.next = null;
this.prev = null;
}
function DoublyLinkedList () {
this.length = 0;
this.head = null;
this.tail = null;
}
DoublyLinkedList.prototype.append = function(pos, ele){
var len = this.length;
if (pos > -1 && pos <= len) {
var node = new Node(ele),
i = 0,
move = this.head;
if (pos == 0) {
if (move) {
node.next = this.head;
this.head = node;
}else {
// 没有元素
this.head = node;
this.tail = node
}
}else if (pos == len) {
// 最后插入
this.tail.next = node;
node.prev = this.tail;
this.tail = this.tail.next;
}else {
while (i != pos) {
i++;
move = move.next;
}
node.prev = move.prev;
move.prev.next = node;
node.next = move;
move.prev = node;
}
this.length++;
return true;
}else {
return false;
}
};
DoublyLinkedList.prototype.removeAt = function(pos){
var len = this.length;
if (pos > -1 && pos < len) {
var i = 0,
previous = this.head,
move = this.head;
if (pos == 0) {
if (len == 1) {
this.head = null;
this.tail = null;
}else {
this.head = this.head.next;
}
}else if(pos == len - 1) {
// 尾部删除
this.tail = this.tail.prev;
this.tail.next = null;
}else {
while (i < pos) {
i++;
previous = move;
move = move.next;
}
previous.next = move.next;
move.next.prev = previous;
}
this.length--;
return true;
}else {
return false;
}
};
DoublyLinkedList.prototype.size = function(){
return this.length;
};
DoublyLinkedList.prototype.toString = function(){
// 转化为字符串
var move = this.head,
str = '';
while (move) {
str += move.element + (move.next ? ' ' : ''); //每个元素之间用空格连接,到了最后一个元素就不用了
move = move.next;
}
return str;
};
var dlist = new DoublyLinkedList();
dlist.append(0,2);
dlist.append(0,5);
dlist.append(0,7);
dlist.append(0,3);
console.log(dlist.toString()); // 3 7 5 2 头插入
dlist.append(4,44);
console.log(dlist.toString()); // 3 7 5 2 44 尾部插入
dlist.append(4,37);
console.log(dlist.toString()); // 3 7 5 2 37 44 中间插入
dlist.removeAt(0);
console.log(dlist.toString()); // 7 5 2 37 44 头部删除
dlist.removeAt(2);
console.log(dlist.toString()); // 7 5 37 44 中间删除
dlist.removeAt(3);
console.log(dlist.toString()); // 7 5 37 尾部删除
/*
var ddlist = new DoublyLinkedList();
ddlist.append(0,1);
ddlist.removeAt(0);
console.log(ddlist.toString()); // 空 只有一个元素删除
*/