Skip to content

Commit

Permalink
Merge pull request #795 from pragatiahuja/master
Browse files Browse the repository at this point in the history
final README
  • Loading branch information
richard-ash authored Aug 29, 2020
2 parents 12a6b93 + 15229cf commit 2fdd8b8
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Linked List/README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,7 @@ This will print the list like so:

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

Iterative Approach:
```swift
public func reverse() {
var node = head
Expand All @@ -482,6 +483,18 @@ How about reversing a list, so that the head becomes the tail and vice versa? Th
}
}
```
Recursive Approach:
```swift
public func reverse(node: head) {
if !head || !head.next {
return head
}
let temp = reverse(head.next)
head.next.next = head
head.next = nil
return temp
}
```

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:

Expand Down

0 comments on commit 2fdd8b8

Please sign in to comment.