Linked list
List is a physical storage unit on a non-continuous, non-sequential storage structure , data element logical sequence through the list of pointer implemented link order. The linked list is composed of a series of nodes (each element in the linked list is called a node), which can be dynamically generated at runtime. Each node includes two parts: one is data element pointer field that stores the address of the next node. [Source Baidu Encyclopedia]
Linked list features
- Use a set of arbitrary memory space to store data elements (the memory space here can be continuous or discontinuous)
- Each node (node) consists of the data itself and a pointer to subsequent nodes
- Access to the entire linked list must start from the head pointer, which points to the first node
- The pointer of the last node points to NULL (NULL)
There are no pointers in JS, and the pointers of the above nodes are just borrowed concepts from the C language.
Linked list complexity
time complexity
Access | Search | Insertion | Deletion | |
---|---|---|---|---|
O(n) | O(n) | O(1) | O(1) |
Space complexity
O(n)
Realization of singly linked list
Several main operations in the linked list
- Initialize linked list/node
- Head insert node
- Search/traverse nodes
- Delete node
- ...
Initialize the node in the linked list
class LinkedListNode {
constructor(value, next = null) {
this.value = value;
this.next = next; // 初始化为null
}
}
Initialize a
class LinkedList {
constructor() {
// 初始空指针
this.head = null;
}
}
Head Append Node (append)
append(value) {
// 新建节点
const newNode = new LinkedListNode(value, this.head);
// 将值赋予head 为了下次新建
this.head = newNode;
}
delete node
delete(value) {
// 如果不存在节点 return null
if (!this.head) {
return null;
}
// 如果删除的是第一个节点
let deletedNode = null;
// 如果删除的第一个元素
while (this.head && this.head.value === value) {
deletedNode = this.head;
this.head = this.head.next;
}
// 非第一个节点,遍历查找
let currentNode = this.head;
if (currentNode !== null) {
while (currentNode.next) {
if (currentNode.next.value === value) {
deletedNode = currentNode.next;
currentNode.next = currentNode.next.next;
} else {
currentNode = currentNode.next;
}
}
}
return deletedNode;
}
Concluding remarks
To make a simple summary, the simple understanding of the linked list structure is that a node contains the current value and the next next. Then initialization is a head. The same structure is added in turn. If you understand it, it will feel very simple. Of course, the linked list is much more than that, there are also doubly linked lists, operations and linked list reverse (reverse), delete (head, tail), conversion data structure and so on.
See you next time.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。