0%

Linklist

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
128
129
130
131
132
/**
* 功能:单链表的插入、删除、查找
* 【插入】:插入到指定元素后方
* 1、查找该元素是否存在?
* 2、没有找到返回 -1
* 3、找到进行创建结点并插入链表。
*
* 【查找】:按值查找/按索引查找
* 1、判断当前结点是否等于null,且是否等于给定值?
* 2、判断是否可以找到该值?
* 3、没有找到返回 -1;
* 4、找到该值返回结点;
*
* 【删除】:按值删除
* 1、判断是否找到该值?
* 2、找到记录前结点,进行删除;
* 3、找不到直接返回-1;
*
*
* 数据域用于存放数据
* 指针域用于存放下一结点地址
*
* 通过数据库访问结点的数据
* 通过指针域访问当前结点的下一结点
* head [1,2]->[3,4]->[5,null]
*/

//定义结点
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}

//定义链表
class LinkList {
constructor() {
//初始化头结点
this.head = new Node("head");
}

//根据 value 查找结点
findByValue = (value) => {
let currentNode = this.head;
while (currentNode !== null && currentNode.data !== value) {
// 一直查找直到找到
currentNode = currentNode.next;
}
//判断该结点是否找到
console.log(currentNode);
return currentNode === null ? -1 : currentNode;
};


//根据 index 查找结点
findByIndex = (index) => {
let pos = 0;
let currentNode = this.head;
while (currentNode !== null && pos !== index) {
currentNode = currentNode.next;
pos++;
}
//判断是否找到该索引
console.log(currentNode);
return currentNode === null ? -1 : currentNode;
};


//插入元素(指定元素向后插入)
insert = (value, element) => {
//先查找该元素
let currentNode = this.findByValue(element);
//如果没有找到
if (currentNode == -1) {
console.log("未找到插入位置!");
return;
}
let newNode = new Node(value);
// currentNode.next 为元素的临时指针
// newNode.next 插入元素的下一个
// 插入元素的下一个指向 存放元素的临时指针
newNode.next = currentNode.next;
// 元素的下一指针指向新元素
currentNode.next = newNode;

};



//根据值删除结点
delete = (value) => {
let currentNode = this.head;
//保留删除节点的前一节点 1->2->3->4
let preNode = null;
while (currentNode !== null && currentNode.data !== value) {
// 删除结点的前一结点
preNode = currentNode;
// 删除结点
currentNode = currentNode.next;
}
if (currentNode == null) return -1;
// 删除结点的前一结点指向删除结点的下一结点
preNode.next = currentNode.next;
};

//遍历所有结点
print = () => {
let currentNode = this.head;
//如果结点不为空
while (currentNode !== null) {
console.log(currentNode.data);
currentNode = currentNode.next;
}
};
}

//测试
const list = new LinkList();
list.insert("xiao", "head");
list.insert("lu", "xiao");
list.insert("ni", "head");
list.insert("hellow", "head");
list.print();
console.log("-------------删除元素------------");
list.delete("ni");
list.delete("xiao");
list.print();
console.log("-------------按值查找------------");
list.findByValue("lu");
console.log("-------------按索引查找------------");
list.print();