Skip to content

Commit 027dc78

Browse files
authored
final README
Add recursive implementation for reversing a singly linked list.
1 parent ba090dc commit 027dc78

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

Linked List/README.markdown

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,7 @@ This will print the list like so:
471471

472472
How about reversing a list, so that the head becomes the tail and vice versa? There is a very fast algorithm for that:
473473

474+
Iterative Approach:
474475
```swift
475476
public func reverse() {
476477
var node = head
@@ -482,6 +483,18 @@ How about reversing a list, so that the head becomes the tail and vice versa? Th
482483
}
483484
}
484485
```
486+
Recursive Approach:
487+
```swift
488+
public func reverse(node: head) {
489+
if (!head || !(head.next)) {
490+
return head
491+
}
492+
let temp = reverse(head.next)
493+
head.next.next = head;
494+
head.next = NULL;
495+
return temp;
496+
}
497+
```
485498

486499
This loops through the entire list and simply swaps the `next` and `previous` pointers of each node. It also moves the `head` pointer to the very last element. (If you had a tail pointer you'd also need to update it.) You end up with something like this:
487500

0 commit comments

Comments
 (0)