Skip to content

Commit 02b70d9

Browse files
moshejstrekhleb
authored andcommitted
Update README.md (trekhleb#162)
Add Pseudocode and Big O notation
1 parent 37c7be1 commit 02b70d9

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

Diff for: src/data-structures/linked-list/README.md

+101
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,107 @@ access, such as random access, is not feasible. Arrays
1818
have better cache locality as compared to linked lists.
1919

2020
![Linked List](https://upload.wikimedia.org/wikipedia/commons/6/6d/Singly-linked-list.svg)
21+
## Pseudocode
22+
23+
### Insert
24+
Add(value)
25+
Pre: value is the value to add to the list
26+
Post: value has been placed at the tail of the list
27+
n ← node(value)
28+
if head = ø
29+
head ← n
30+
tail ← n
31+
else
32+
tail.next ← n
33+
tail ← n
34+
end if
35+
end Add
36+
37+
### Search
38+
Contains(head, value)
39+
Pre: head is the head node in the list
40+
value is the value to search for
41+
Post: the item is either in the linked list, true; otherwise false
42+
n ← head
43+
while n = ø and n.value = value
44+
n ← n.next
45+
end while
46+
if n = ø
47+
return false
48+
end if
49+
return true
50+
end Contains
51+
52+
### Delete
53+
Remove(head, value)
54+
Pre: head is the head node in the list
55+
Post: value is the value to remove from the list, true, otherwise false
56+
if head = ø
57+
return false
58+
end if
59+
n ← head
60+
if n.value = value
61+
if head = tail
62+
head ← ø
63+
tail ← ø
64+
else
65+
head ← head.next
66+
end if
67+
return true
68+
end if
69+
while n.next = ø and n.next.value = value
70+
n ← n.next
71+
end while
72+
if n.next = ø
73+
if n.next = tail
74+
tail ← n
75+
end if
76+
n.next ← n.next.next
77+
return true
78+
end if
79+
return false
80+
end Remove
81+
82+
### Traverse
83+
Traverse(head)
84+
Pre: head is the head node in the list
85+
Post: the items in the list have been traversed
86+
n ← head
87+
while n = 0
88+
yield n.value
89+
n ← n.next
90+
end while
91+
end Traverse
92+
93+
### Traverse in Reverse
94+
ReverseTraversal(head, tail)
95+
Pre: head and tail belong to the same list
96+
Post: the items in the list have been traversed in reverse order
97+
if tail = ø
98+
curr ← tail
99+
while curr = head
100+
prev ← head
101+
while prev.next = curr
102+
prev ← prev.next
103+
end while
104+
yield curr.value
105+
curr ← prev
106+
end while
107+
yeild curr.value
108+
end if
109+
end ReverseTraversal
110+
111+
112+
## Big *O*
113+
114+
### Time Complexity
115+
Access: *O*(*n*) \
116+
Search: *O*(*n*) \
117+
Insert: *O*(1) \
118+
Delete: *O*(1)
119+
120+
### Space Complexity
121+
*O*(*n*)
21122

22123
## References
23124

0 commit comments

Comments
 (0)