官术网_书友最值得收藏!

Doubly linked list

The transaction log of the previous section is due for an upgrade. The product team wants to enable users to be able to examine the log by going through it forward and backward to see what each step does. This is bad news for the regular linked list, as it's really inefficient to go anywhere other than forward. So, how is this rectified?

It is rectified using the doubly linked list. The doubly linked list introduces the link back. While this sounds like a minor change, it allows to work on that list backward as well as forward, which significantly improves the ability to look up items. By augmenting the previous singly linked list item with a back pointer, the doubly linked list is almost created:

#[derive(Debug, Clone)]
struct Node {
value: String,
next: Link,
prev: Link,
}

type Link = Option<Rc<RefCell<Node>>>;

#[derive(Debug, Clone)]
pub struct BetterTransactionLog {
head: Link,
tail: Link,
pub length: u64,
}

Similar to the singly linked list, the list itself only consists of a head and a tail pointer, which makes accessing either end of the list cheap and easy. Additionally, the nodes now also feature a pointer back to the preceding node, making the list look like this:

This is also the point that makes the doubly linked list tricky in Rust. The ownership principle is great if there is a hierarchy of ownership: a customer has an address, a text file has several lines of text, and so on. However, a node in a doubly linked list doesn't have clear ownership of either of its neighbors.

主站蜘蛛池模板: 兰州市| 达日县| 横峰县| 全州县| 乌拉特后旗| 木里| 伊金霍洛旗| 巴东县| 宁明县| 永年县| 胶州市| 九江县| 新郑市| 蒙阴县| 大庆市| 山西省| 玛曲县| 台南市| 广宗县| 晋城| 阿拉善盟| 库尔勒市| 黑龙江省| 郯城县| 靖安县| 济宁市| 兴山县| 监利县| 临清市| 宝山区| 称多县| 海丰县| 老河口市| 江阴市| 沐川县| 扎赉特旗| 邢台市| 井冈山市| 乌鲁木齐市| 淄博市| 德昌县|