Skip to content

Commit 53de9d4

Browse files
authored
Update linked-list.md
Added function reverseList
1 parent 7ce4edc commit 53de9d4

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

contrib/ds-algorithms/linked-list.md

+25-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Linked List Data Structure
22

3-
Link list is a linear data Structure which can be defined as collection of objects called nodes that are randomly stored in the memory.
3+
Linked list is a linear data Structure which can be defined as collection of objects called nodes that are randomly stored in the memory.
44
A node contains two types of metadata i.e. data stored at that particular address and the pointer which contains the address of the next node in the memory.
55

66
The last element in a linked list features a null pointer.
@@ -36,10 +36,10 @@ The smallest Unit: Node
3636
Now, we will see the types of linked list.
3737

3838
There are mainly four types of linked list,
39-
1. Singly Link list
40-
2. Doubly link list
41-
3. Circular link list
42-
4. Doubly circular link list
39+
1. Singly linked list
40+
2. Doubly linked list
41+
3. Circular linked list
42+
4. Doubly circular linked list
4343

4444

4545
## 1. Singly linked list.
@@ -160,6 +160,18 @@ check the list is empty otherwise shift the head to next node.
160160
temp.next = None # Remove the last node by setting the next pointer of the second-last node to None
161161
```
162162

163+
### Reversing the linked list
164+
```python
165+
def reverseList(self):
166+
prev = None
167+
temp = self.head
168+
while(temp):
169+
nextNode = temp.next #Store the next node
170+
temp.next = prev #Reverse the pointer of current node
171+
prev = temp #Move `prev` one step forward
172+
temp = nextNode #Move `temp` one step forward.
173+
self.head = prev #Update the head pointer to last node
174+
```
163175

164176
### Search in a linked list
165177
```python
@@ -174,6 +186,8 @@ check the list is empty otherwise shift the head to next node.
174186
return f"Value '{value}' not found in the list"
175187
```
176188

189+
Connect all the code.
190+
177191
```python
178192
if __name__ == '__main__':
179193
llist = LinkedList()
@@ -197,13 +211,17 @@ check the list is empty otherwise shift the head to next node.
197211

198212
#delete at the end
199213
llist.deleteFromEnd() # 2 3 56 9 4 10
200-
# Print the list
214+
# Print the original list
215+
llist.printList()
216+
llist.reverseList() #10 4 9 56 3 2
217+
# Print the reversed list
201218
llist.printList()
202219
```
203220
## Output:
204221

205-
2 3 56 9 4 10
222+
2 3 56 9 4 10
206223

224+
10 4 9 56 3 2
207225

208226

209227
## Real Life uses of Linked List

0 commit comments

Comments
 (0)