github.com/trekhleb/ja… 的学习笔记
链表是数据元素的线性集合,但他不是像数组那样连续储存在内存中,每个链表元素都由他自己的值和指向下一个元素的引用组成。他可以插入或删除指定的元素,但由于他的访问只能是线性的,它要访问一个元素,就要从头开始遍历直到找到该元素,不能像数组那样快速的随机访问。

基本操作
插入
Add(value)
Pre: value is the value to add to the list
Post: value has been placed at the tail of the list
n ← node(value)
if head = ø
head ← n
trail ← n
else
trail.next = n
trail ← n
end if
end Add
Prepend(value)
Pre: value is the value to add to the list
Post: value has been placed at the head of the list
n ← node(value)
n.next ← head
n ← head
if trail = ø
trail ← n
end
end Perepend
搜索
Contains(head, value)
Pre: head is the head node in the list
value is the value to search for
Post: the item is either in the linked list, true; otherwise false
n ← head
if n = ø
return false
while (n != ø and n.value != value)
n ← n.next
end while
if (n = ø)
return false
end if
return true
删除
Remove(head, value)
Pre: head is the head node in the list
value is the value to remove from the list
Post: value is removed from the list, true, otherwise false
n ← head
if n = ø
return false
end if
if n.value = value
if head = trail
head ← ø
trail ← ø
else
head ← head.next
return true
end if
while n.next != ø and n.next.value != value
n ← n.next
end while
if n.next != ø
if trail = n.next
trail ← n
end if
n.next ← n.next.next
return true
end if
else
return false
end Remove
遍历
Traverse(head)
Pre: head is the head node in the list
Post: the items in the list have been traversed
n ← head
while n != ø
yield n.value
n ← n.next
end while
end Traverse
反向遍历
ReverseTraversal(head, trail)
Pre: head and tail belong to the same list
Post: the items in the list have been traversed in reverse order
if trail != ø
curr = trail
while head != curr
prev ← head
while prev.next != curr
prev ← prev.next
end while
yield curr.value
curr ← prev
end while
yield curr.value
end if
end ReverseTraversal
复杂度
时间复杂度
| 访问 | 搜索 | 插入 | 删除 |
|---|---|---|---|
| O(n) | O(n) | O(1) | O(n) |
空间复杂度
O(n)