Skip to content

Commit 48e383c

Browse files
committed
[A] list: LinkedList
1 parent 8be55a1 commit 48e383c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# LinkedList
2+
3+
## 时间复杂度
4+
5+
## 下标操作
6+
7+
任何带下标的操作操作基本都是 O(n/2) ~ O(n)
8+
9+
```java
10+
/**
11+
* Returns the (non-null) Node at the specified element index.
12+
*/
13+
Node<E> node(int index) {
14+
// assert isElementIndex(index);
15+
16+
if (index < (size >> 1)) {
17+
// 如果 index 小于 size 的一半,则从往后遍历
18+
Node<E> x = first;
19+
for (int i = 0; i < index; i++)
20+
x = x.next;
21+
return x;
22+
} else {
23+
// 如果 index 大于 size 的一半,则从后往前遍历
24+
Node<E> x = last;
25+
for (int i = size - 1; i > index; i--)
26+
x = x.prev;
27+
return x;
28+
}
29+
}
30+
```
31+
32+
## 双向链表
33+
34+
```java
35+
/**
36+
* Pointer to first node.
37+
* Invariant: (first == null && last == null) ||
38+
* (first.prev == null && first.item != null)
39+
*/
40+
transient Node<E> first;
41+
42+
/**
43+
* Pointer to last node.
44+
* Invariant: (first == null && last == null) ||
45+
* (last.next == null && last.item != null)
46+
*/
47+
transient Node<E> last;
48+
49+
private static class Node<E> {
50+
E item;
51+
Node<E> next;
52+
Node<E> prev;
53+
54+
Node(Node<E> prev, E element, Node<E> next) {
55+
this.item = element;
56+
this.next = next;
57+
this.prev = prev;
58+
}
59+
}
60+
```
61+
62+
## 最后
63+
64+
没啥好说的很简单

0 commit comments

Comments
 (0)